/**
  * 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;
 }
Exemple #2
0
 /**
  * Logs with an arbitrary level.
  *
  * @param mixed $level
  * @param string $message
  * @param array $context
  * @return null
  */
 public function log($level, $message, array $context = array())
 {
     // add color to all injected variables
     $message = preg_replace_callback('/{([\\w\\d_\\.]+)}/is', function ($matches) {
         $var = $matches[1];
         return '<info>{' . $var . '}</info>';
     }, $message);
     $message = StringUtils::interpolate($message, $context);
     $alert = '';
     switch ($level) {
         case LogLevel::ALERT:
         case LogLevel::CRITICAL:
         case LogLevel::EMERGENCY:
         case LogLevel::ERROR:
             $alert = '<error> ' . $level . ' </error> ';
             break;
         case LogLevel::NOTICE:
         case LogLevel::WARNING:
             $alert = '<fg=yellow;options=bold>' . $level . '</fg=yellow;options=bold> ';
             break;
     }
     $this->output->writeln($alert . $message . '     [@mem: ' . StringUtils::bytesToString(Timer::getCurrentMemory()) . ']');
 }
 public function testBytesToString()
 {
     $this->assertEquals('0 b', StringUtils::bytesToString(0));
     $this->assertEquals('1000 b', StringUtils::bytesToString(1000));
     $this->assertEquals('1 kb', StringUtils::bytesToString(1024));
     $this->assertEquals('1 kb', StringUtils::bytesToString(1025));
     $this->assertEquals('500 kb', StringUtils::bytesToString(1024 * 500));
     $this->assertEquals('1.0 MB', StringUtils::bytesToString(1024 * 1024));
     $this->assertEquals('1.5 MB', StringUtils::bytesToString(1024 * 1024 * 1.5));
     $this->assertEquals('1.25 GB', StringUtils::bytesToString(1024 * 1024 * 1024 * 1.25));
 }
 /**
  * Renders the final response and sends it back to the client.
  * 
  * @param Response $response HTTP Response to be sent.
  * @param Request $request The original HTTP request for context.
  */
 public function sendResponse(Response $response, Request $request)
 {
     // prepare the response for sending (will tweak some headers based on the request)
     $response->prepare($request);
     // trigger WillSendResponse event for any last minute changes
     $this->container->get('event_manager')->trigger(new WillSendResponse($response, $request));
     $timer = $this->container->get('splot.timer');
     $time = $timer->getDuration();
     $memory = $timer->getCurrentMemoryPeak();
     $memoryString = StringUtils::bytesToString($memory);
     $this->logger->debug('Rendering response for {method} {uri} took {time} ms and used {memory} memory.', array('method' => $request->getMethod(), 'uri' => $request->getRequestUri(), 'memory' => $memoryString, 'time' => $time, '@stat' => 'splot.render', '@time' => $time, '@memory' => $memory));
     // and finally send out the response
     $response->send();
 }
Exemple #5
0
 /**
  * Runs the application in context of the given mode and using the given runner function.
  *
  * The last argument is a callback that will be invoked by this method and it should contain
  * execution logic specific to the given mode.
  *
  * Returns whatever the runner returns (which should be a result of running the application).
  * 
  * @param  AbstractApplication $application Application to be ran.
  * @param  int                 $mode        Mode in which the application should be ran.
  *                                          One of the `Framework::MODE_*` constants.
  * @param  callable            $runner      Closure that is responsible for actually running
  *                                          the application in appropriate mode.
  * @return mixed
  */
 protected function doRunApplication(AbstractApplication $application, $mode, $runner)
 {
     $timer = new Timer();
     $container = $application->getContainer();
     // container can now know in what mode its running
     $container->setParameter('mode', $mode);
     // run modules and the app
     foreach ($application->getModules() as $module) {
         $module->run();
     }
     $application->run();
     // run using the passed runner
     $result = call_user_func($runner);
     // log benchmark data
     $time = $timer->stop();
     $memory = $timer->getMemoryUsage();
     $container->get('splot.logger')->debug('Application run phase in mode "{mode}" finished in {time} ms and used {memory} memory.', array('mode' => self::modeName($mode), 'env' => $container->getParameter('env'), 'debug' => $container->getParameter('debug'), 'time' => $time, 'memory' => StringUtils::bytesToString($memory), '@stat' => 'splot.run.' . self::modeName($mode), '@time' => $time, '@memory' => $memory));
     return $result;
 }