public function remove($filename)
 {
     if (empty($filename)) {
         throw new \LogicException('File name can not be empty string.');
     }
     $this->fs->remove($this->uploadDir->getRealPath() . '/' . $filename);
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $namespace = false;
     $classyName = null;
     $classyIndex = 0;
     foreach ($tokens as $index => $token) {
         if ($token->isGivenKind(T_NAMESPACE)) {
             if (false !== $namespace) {
                 return;
             }
             $namespace = true;
         } elseif ($token->isClassy()) {
             if (null !== $classyName) {
                 return;
             }
             $classyIndex = $tokens->getNextMeaningfulToken($index);
             $classyName = $tokens[$classyIndex]->getContent();
         }
     }
     if (null === $classyName) {
         return;
     }
     if (false !== $namespace) {
         $filename = basename(str_replace('\\', '/', $file->getRealPath()), '.php');
         if ($classyName !== $filename) {
             $tokens[$classyIndex]->setContent($filename);
         }
     } else {
         $normClass = str_replace('_', '/', $classyName);
         $filename = substr(str_replace('\\', '/', $file->getRealPath()), -strlen($normClass) - 4, -4);
         if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) {
             $tokens[$classyIndex]->setContent(str_replace('/', '_', $filename));
         }
     }
 }
 /**
  * installFilesystem
  *
  * Install's
  *
  * @param SiteInterface $site
  */
 public function installFilesystem(SiteInterface $site)
 {
     if (!$site->getId()) {
         $this->getSiteManager()->save($site);
     }
     if ($site->getAliasOf()) {
         return $this->installFilesystem($site->getAliasOf());
     }
     $baseDir = new \SplFileInfo($this->getKernel()->getRootDir() . '/../');
     $skelDir = $baseDir->getRealPath() . '/skeleton/site';
     $skelWebDir = $baseDir->getRealPath() . '/skeleton/site/web';
     $vhostDir = $baseDir->getRealPath() . '/vhosts';
     $templateDir = $baseDir->getRealPath() . '/templates';
     $siteDir = $vhostDir . '/' . preg_replace('/^www\\./', '', $site->getDomain());
     $siteWebDir = $siteDir . '/web';
     $siteTemplateDir = $siteDir . '/templates';
     $site->setRootDir($siteDir)->setWebDir($siteWebDir)->setTemplateDir($siteTemplateDir);
     if (!file_exists($siteDir)) {
         $process = new Process(sprintf('cp -r %s %s', $skelDir, $siteDir));
         $process->run();
         if (!$process->isSuccessful()) {
             throw new \RuntimeException($process->getErrorOutput());
         }
     }
     file_put_contents($siteWebDir . '/config.php', str_replace(array('[id]', '[domain]'), array($site->getId(), $site->getDomain()), file_get_contents($skelWebDir . '/config.php')));
     $this->getSiteManager()->save($site);
 }
Example #4
0
 /**
  * Upload an image to local server then return new image path after upload success
  * 
  * @param array $file [tmp_name, name, error, type, size] 
  * @param string image path for saving (this may constain filename)
  * @param string image filename for saving
  * @return string Image path after uploaded
  * @throws Exception If upload failed
  */
 public function upload($file, $newImagePath = '.', $newImageName = NULL)
 {
     if (!empty($file['error'])) {
         $this->_throwException(':method: Upload error. Number: :number', array(':method' => __METHOD__, ':number' => $file['error']));
     }
     if (getimagesize($file['tmp_name']) === FALSE) {
         $this->_throwException(':method: The file is not an image file.', array(':method' => __METHOD__));
     }
     $fileInfo = new \SplFileInfo($newImagePath);
     if (!$fileInfo->getRealPath() or !$fileInfo->isDir()) {
         $this->_throwException(':method: The ":dir" must be a directory.', array(':method' => __METHOD__, ':dir' => $newImagePath));
     }
     $defaultExtension = '.jpg';
     if (empty($newImageName)) {
         if (!in_array($fileInfo->getBasename(), array('.', '..')) and $fileInfo->getExtension()) {
             $newImageName = $fileInfo->getBasename();
         } else {
             $newImageName = uniqid() . $defaultExtension;
         }
     }
     if (!$fileInfo->isWritable()) {
         $this->_throwException(':method: Directory ":dir" is not writeable.', array(':method' => __METHOD__, ':dir' => $fileInfo->getRealPath()));
     }
     $destination = $fileInfo->getRealPath() . DIRECTORY_SEPARATOR . $newImageName;
     if (move_uploaded_file($file['tmp_name'], $destination)) {
         return $destination;
     } else {
         $this->_throwException(':method: Cannot move uploaded file to :path', array(':method' => __METHOD__, ':path' => $fileInfo->getRealPath()));
     }
 }
Example #5
0
 public function export()
 {
     $zipFile = PHPFOX_DIR_FILE . 'static/' . uniqid() . '.zip';
     $zipArchive = new \ZipArchive();
     if (!$zipArchive->open($zipFile, \ZIPARCHIVE::OVERWRITE)) {
         throw new \Exception('Unable to create ZIP archive.');
     }
     $exclude = array('.git');
     $filter = function ($file, $key, $iterator) use($exclude) {
         if ($file->getFileName() == 'app.lock' || $file->getFileName() == 'composer.phar') {
             return false;
         }
         if ($iterator->hasChildren() && !in_array($file->getFilename(), $exclude)) {
             return true;
         }
         return $file->isFile();
     };
     $directory = new \SplFileInfo($this->path);
     $innerIterator = new \RecursiveDirectoryIterator($directory->getRealPath(), \RecursiveDirectoryIterator::SKIP_DOTS);
     $files = new \RecursiveIteratorIterator(new \RecursiveCallbackFilterIterator($innerIterator, $filter));
     foreach ($files as $name => $file) {
         if ($file instanceof \SplFileInfo) {
             $filePath = $file->getRealPath();
             $name = str_replace($directory->getRealPath(), '', $filePath);
             $zipArchive->addFile($filePath, $name);
         }
     }
     $zipArchive->close();
     $name = \Phpfox_Parse_Input::instance()->cleanFileName($this->id);
     $name .= '-v' . $this->version;
     \Phpfox_File::instance()->forceDownload($zipFile, 'phpfox-app-' . $name . '.zip');
     return $zipFile;
 }
 /**
  * @return string
  */
 public function getRealPath()
 {
     $SplFileInfo = new \SplFileInfo($this->Instance->getLocation());
     if (!$SplFileInfo->getRealPath()) {
         $SplFileInfo = new \SplFileInfo($_SERVER['DOCUMENT_ROOT'] . $this->Instance->getLocation());
     }
     return $SplFileInfo->getRealPath() ? $SplFileInfo->getRealPath() : '';
 }
Example #7
0
 public function __construct($filename)
 {
     $file = new \SplFileInfo($filename);
     $this->filename = $filename;
     if (file_exists($file->getRealPath())) {
         @unlink($file->getRealPath());
     }
     $this->phar = new \Phar($file->getPathname(), 0, $file->getFilename());
 }
Example #8
0
 /**
  * Hash constructor.
  * creates a new hash set from a list of files
  *
  * @constructor
  * @access public
  * @param array $fileList
  */
 public function __construct(array $fileList)
 {
     $this->fileList = $fileList;
     foreach ($this->fileList as $filePath) {
         $file = new \SplFileInfo($filePath);
         // hash the file path, size and CTime using murmur
         $this->hashSet[$file->getRealPath()] = murmurhash3($file->getRealPath() . $file->getSize() . $file->getCTime());
     }
 }
Example #9
0
File: Set.php Project: eexit/smak
 /**
  * Class constructor
  * 
  * @param \SplFileInfo $set_info Set file info
  */
 public function __construct(\SplFileInfo $set_info)
 {
     parent::__construct();
     $this->set_path = $set_info->getRealPath();
     $this->name = $set_info->getFilename();
     $this->files()->in($set_info->getRealPath())->ignoreDotFiles(true);
     foreach ($this->allowed_ext as $ext) {
         $this->name(sprintf('/%s$/i', $ext));
     }
 }
 /**
  *
  * @param string $filename
  *
  * @return \CSanquer\FakeryGenerator\Model\Config
  *
  * @throws \InvalidArgumentException
  */
 public function load($filename)
 {
     $file = new \SplFileInfo($filename);
     if (!in_array($file->getExtension(), ['json', 'xml'])) {
         throw new \InvalidArgumentException('The config file must be an XML or a JSON file.');
     }
     if (!file_exists($file->getRealPath())) {
         throw new \InvalidArgumentException('The config file must exist.');
     }
     return $this->serializer->deserialize(file_get_contents($file->getRealPath()), 'CSanquer\\FakeryGenerator\\Model\\Config', $file->getExtension());
 }
 public function parse(\SplFileInfo $file)
 {
     $namespaceExtractor = new NamespaceExtractor();
     $classNameExtractor = new ClassNameExtractor();
     $useDeclarationExtractor = new UseDeclarationsExtractor();
     $content = file_get_contents($file->getRealPath());
     $tokens = Tokens::fromCode($content);
     $classNamespace = $namespaceExtractor->extract($tokens);
     $className = $classNameExtractor->extract($tokens);
     $classFullName = sprintf('%s\\%s', $classNamespace, $className);
     $useDeclarations = $useDeclarationExtractor->extract($tokens);
     return new Node($useDeclarations, $classFullName, $file->getRealPath(), NodeInterface::TYPE_PHP_USE);
 }
Example #12
0
 protected function __construct($path, $fn, $delimiter)
 {
     $this->delimiter = $delimiter;
     if (substr($path, -1) != DIRECTORY_SEPARATOR) {
         $path .= DIRECTORY_SEPARATOR;
     }
     $conf_file = new \SplFileInfo($path . $fn);
     if (!$conf_file->isReadable()) {
         $conf_file = new \SplFileInfo($path . $fn . '.dist');
         if (!$conf_file->isReadable()) {
             throw new UnreadableConfigException($conf_file->getRealPath());
         }
     }
     $this->data = Yaml::parse(file_get_contents($conf_file->getRealPath()));
 }
Example #13
0
File: File.php Project: yunaid/yf
 /**
  * Get a stored value
  * @param string $group
  * @param string $name
  * @param mixed $default
  * @return mixed
  */
 public function get($group, $name, $default = NULL)
 {
     // explode on separator
     $parts = explode($this->params['separator'], $name);
     // add group to front
     array_unshift($parts, $group);
     // last part is filename
     $filename = array_pop($parts) . '.cache';
     // get directory
     $directory = $this->dir->getRealPath() . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $parts) . DIRECTORY_SEPARATOR;
     // get file
     $file = new \SplFileInfo($directory . $filename);
     if (!$file->isFile()) {
         // file doesnt exist: return default
         return $default;
     } else {
         // get time created
         $created = $file->getMTime();
         // get data handle
         $data = $file->openFile();
         // lifetime is the first line
         $lifetime = $data->fgets();
         if ($data->eof()) {
             // end of file: cache is corrupted: delete it and return default
             unlink($file->getRealPath());
             return $default;
         }
         // read data lines
         $cache = '';
         while ($data->eof() === FALSE) {
             $cache .= $data->fgets();
         }
         if ($created + (int) $lifetime < time()) {
             // Expired: delete the file & return default
             unlink($file->getRealPath());
             return $default;
         } else {
             try {
                 $unserialized = unserialize($cache);
             } catch (Exception $e) {
                 // Failed to unserialize: delete file and return default
                 unlink($file->getRealPath());
                 $unserialized = $default;
             }
             return $unserialized;
         }
     }
 }
Example #14
0
 protected function createTransferAction(\SplFileInfo $file)
 {
     // Open the file for reading
     $filename = $file->getRealPath() ?: $file->getPathName();
     if (!($resource = fopen($filename, 'r'))) {
         // @codeCoverageIgnoreStart
         throw new RuntimeException('Could not open ' . $file->getPathname() . ' for reading');
         // @codeCoverageIgnoreEnd
     }
     $key = $this->options['source_converter']->convert($filename);
     $body = EntityBody::factory($resource);
     // Determine how the ACL should be applied
     if ($acl = $this->options['acl']) {
         $aclType = is_string($this->options['acl']) ? 'ACL' : 'ACP';
     } else {
         $acl = 'private';
         $aclType = 'ACL';
     }
     // Use a multi-part upload if the file is larger than the cutoff size and is a regular file
     if ($body->getWrapper() == 'plainfile' && $file->getSize() >= $this->options['multipart_upload_size']) {
         $builder = UploadBuilder::newInstance()->setBucket($this->options['bucket'])->setKey($key)->setMinPartSize($this->options['multipart_upload_size'])->setOption($aclType, $acl)->setClient($this->options['client'])->setSource($body)->setConcurrency($this->options['concurrency']);
         $this->dispatch(self::BEFORE_MULTIPART_BUILD, array('builder' => $builder, 'file' => $file));
         return $builder->build();
     }
     return $this->options['client']->getCommand('PutObject', array('Bucket' => $this->options['bucket'], 'Key' => $key, 'Body' => $body, $aclType => $acl));
 }
 public function getHash()
 {
     if (!$this->isReadable()) {
         throw new InvalidConfigurationException('Cannot read from file ' . $this->file);
     }
     return md5_file($this->file->getRealPath());
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getOption('filename');
     if (!$filename) {
         $resource = STDIN;
     } else {
         try {
             $file = new \SplFileInfo($filename);
         } catch (\Exception $e) {
             throw new \InvalidArgumentException('Bad filename');
         }
         $resource = fopen($file->getRealPath(), 'rb');
     }
     $width = $input->getArgument('width');
     $height = $input->getArgument('height');
     $dim = $input->getArgument('dim');
     if (!$width) {
         $width = VisualizationEqualizer::WIDTH_DEFAULT;
     }
     if (!$height) {
         $height = VisualizationEqualizer::HEIGHT_DEFAULT;
     }
     if (!$dim) {
         $dim = VisualizationEqualizer::DIM_DEFAULT;
     }
     $render = new ConsoleRender($output);
     $render->setDisplayColor(true);
     $wavReader = new WavReader($resource, new Riff(), new Fmt(), new Data());
     $visualizationEqualizer = new VisualizationEqualizer($resource, $dim, $wavReader, $render);
     $visualizationEqualizer->run((int) $width, (int) $height);
 }
Example #17
0
    public function __construct(SplFileInfo $fileinfo = null)
    {
        parent::__construct();
        if ($fileinfo) {
            $this->file_hash = md5($fileinfo->getRealPath());
            $fileSize = $fileinfo->getSize();
            // Looking for existing path
            $result = Db::getInstance()->getRow('
				SELECT *
				FROM `' . _DB_PREFIX_ . bqSQL(self::$definition['table']) . '`
				WHERE `file_hash` = \'' . pSQL($this->file_hash) . '\'');
            if (!$result) {
                $this->file_size = $fileSize;
                $this->file_info = $fileinfo;
            } else {
                $this->id = $result['id'];
                foreach ($result as $key => $value) {
                    if (array_key_exists($key, $this)) {
                        $this->{$key} = $value;
                    }
                }
                // Check file size
                if ($this->file_size != $fileSize) {
                    $this->file_size = $fileSize;
                    $this->file_info = $fileinfo;
                }
            }
        }
        return $this;
    }
Example #18
0
 private function addFile(\Phar $phar, \SplFileInfo $file)
 {
     $path = str_replace(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR, '', $file->getRealPath());
     $content = file_get_contents($file);
     $content = $this->stripWhitespace($content);
     $phar->addFromString($path, $content);
 }
Example #19
0
 /**
  * Performs a check of file
  *
  * @param \SplFileInfo $file File to check
  *
  * @return bool
  */
 public function __invoke(\SplFileInfo $file)
 {
     $rootDirectory = $this->rootDirectory;
     $includePaths = $this->includePaths;
     $excludePaths = $this->excludePaths;
     if ($file->getExtension() !== 'php') {
         return false;
     }
     $realPath = $file->getRealPath();
     // Do not touch files that not under rootDirectory
     if (strpos($realPath, $rootDirectory) !== 0) {
         return false;
     }
     if ($includePaths) {
         $found = false;
         foreach ($includePaths as $includePath) {
             if (strpos($realPath, $includePath) === 0) {
                 $found = true;
                 break;
             }
         }
         if (!$found) {
             return false;
         }
     }
     foreach ($excludePaths as $excludePath) {
         if (strpos($realPath, $excludePath) === 0) {
             return false;
         }
     }
     return true;
 }
Example #20
0
 /**
  * Returns the true filesystem path for a file.
  *
  * @return string The path to the file on the filesystem.
  */
 public function getRealPath()
 {
     if ($this->_reference) {
         return $this->_getPathFromRef($this->_reference);
     }
     return parent::getRealPath();
 }
Example #21
0
 /**
  * Parse the given file to check potential errors.
  *
  * @param \SplFileInfo $file
  */
 public function parse(\SplFileInfo $file)
 {
     try {
         $content = file_get_contents($file->getRealPath());
         if (strlen($content) > 0) {
             // Keep the context up to date
             $this->parserContext->setFilename($file->getRealPath());
             // Parse the file content
             $stmts = $this->parser->parse($content);
             // Traverse the statements
             $this->traverser->traverse($stmts);
         }
     } catch (PhpParserError $e) {
         echo 'Parse Error: ', $e->getMessage();
     }
 }
Example #22
0
 /**
  * @param \SplFileInfo $file
  *
  * @return \Spryker\Zed\Product\Business\Model\ProductBatchResult
  */
 public function importFile(\SplFileInfo $file)
 {
     $totalCount = 0;
     $batchIterator = new CsvBatchIterator($file->getRealPath(), 10);
     foreach ($batchIterator as $batchCollection) {
         foreach ($batchCollection as $productDataToImport) {
             $preProcessedProduct = $this->preProcess($productDataToImport);
             if (empty($preProcessedProduct)) {
                 $this->logInvalidProduct($productDataToImport);
                 continue;
                 //skip invalid products
             }
             $product = $this->process($preProcessedProduct);
             $result = $this->afterProcess($product);
             $totalCount++;
             if (!$result) {
                 $this->logNotImportableProduct($productDataToImport);
             }
         }
     }
     $result = clone $this->productBatchResult;
     $result->setTotalCount($totalCount);
     $result->setFailedCount(count($this->invalidProducts));
     return $result;
 }
Example #23
0
 public function importSingleMovie(\SplFileInfo $source)
 {
     if (!$source->isReadable()) {
         return $this->output->writelnError(sprintf("File %s not readable", $source->getFilename()));
     }
     $this->output->writelnInfo(sprintf("Importing %s ...", $source->getRealPath()));
     $file = $source->openFile();
     /** @var Movies $movie */
     $movie = $this->getMovie($file->fread($file->getSize()), $file->getBasename('.html'));
     if (!$movie) {
         return $this->output->writelnError(sprintf("Not found dmm id", $source->getFilename()));
     }
     $this->currentDmmId = $movie->banngo;
     if (Movies::findFirstById($movie->id)) {
         return $this->output->writelnWarning(sprintf("Movie %s already exists, insert skipped", $movie->banngo));
     }
     /** @var Mysql $db */
     $db = $this->getDI()->get('dbMaster');
     $db->begin();
     if (false === $movie->save()) {
         $db->rollback();
         return $this->output->writelnError(sprintf("Movie saving failed by %s", implode(',', $movie->getMessages())));
     }
     $db->commit();
     $this->output->writelnSuccess(sprintf("Movie %s saving success as %s, detail: %s", $movie->banngo, $movie->id, ''));
 }
Example #24
0
 /**
  * Load config data. Support php|ini|yml config formats.
  *
  * @param string|\SplFileInfo $configFile
  * @throws ConfigException
  */
 public function loadConfig($configFile)
 {
     if (!$configFile instanceof \SplFileInfo) {
         if (!is_string($configFile)) {
             throw new ConfigException('Mismatch type of variable.');
         }
         $path = realpath($this->basePath . $configFile);
         // check basePath at mutation
         if (strpos($configFile, '..') || !strpos($path, realpath($this->basePath))) {
             throw new ConfigException('Config file name: ' . $configFile . ' isn\'t correct.');
         }
         if (!is_file($path) || !is_readable($path)) {
             throw new ConfigException('Config file: ' . $path . ' not found of file isn\'t readable.');
         }
         $configFile = new \SplFileInfo($path);
     }
     $path = $configFile->getRealPath();
     $ext = $configFile->getExtension();
     $key = $configFile->getBasename('.' . $ext);
     if ('php' === $ext) {
         $this->data[$key] = (include $path);
     } elseif ('ini' === $ext) {
         $this->data[$key] = parse_ini_file($path, true);
     } elseif ('yml' === $ext) {
         if (!function_exists('yaml_parse_file')) {
             throw new ConfigException("Function `yaml_parse_file` isn't supported.\n" . 'http://php.net/manual/en/yaml.requirements.php');
         }
         $this->data[$key] = yaml_parse_file($path);
     }
 }
 /**
  *
  */
 public function testCommandLineExecute()
 {
     /** @var OrganizeCommand $command */
     $outputDir = __DIR__;
     $fildir = realpath(__DIR__ . '/../');
     $bin = realpath(__DIR__ . '/../../src/bin/organize');
     $cmd = "find {$fildir} -type f -name '*.mp3' -exec {$bin} organizer:files {$outputDir} {} \\;";
     $output = trim(shell_exec($cmd));
     $dest = new \SplFileInfo($output);
     $this->assertContains('Celtic', $dest->getRealPath());
     $this->assertTrue(true, is_file($output));
     $this->assertContains('2003', $dest->getRealPath());
     rename($dest->getRealPath(), Helper::getSampeMp3File());
     $fs = new Filesystem();
     $fs->remove(__DIR__ . '/2003/');
 }
Example #26
0
 public function __construct(SplFileInfo $file)
 {
     $this->file = $file;
     $this->location = $file->getRealPath();
     $this->name = preg_replace('/\\.' . preg_quote(General::getExtension($file)) . '$/', null, $file->getFilename());
     $this->errors = array();
 }
Example #27
0
 public function analyze(\SplFileInfo $file)
 {
     $path = $file->getRealPath();
     if (!$path || !($metadata = getimagesize($path))) {
         throw new AnalysisFailedException(sprintf('Unable to extract image metadata for path %s.', $path));
     }
     return ['width' => $metadata[0], 'height' => $metadata[1]];
 }
 /**
  * Get the configuration file nesting path.
  *
  * @param  \Symfony\Component\Finder\SplFileInfo  $file
  * @return string
  */
 private function getConfigurationNesting(\SplFileInfo $file)
 {
     $directory = dirname($file->getRealPath());
     if ($tree = trim(str_replace($this->config_path, '', $directory), DIRECTORY_SEPARATOR)) {
         $tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.';
     }
     return $tree;
 }
Example #29
0
 /**
  * Returns the details about Communicator (current) file
  * w/o any kind of verification of file existance
  *
  * @param string $fileGiven
  * @return array
  */
 protected function getFileDetailsRaw($fileGiven)
 {
     $info = new \SplFileInfo($fileGiven);
     $aFileBasicDetails = ['File Extension' => $info->getExtension(), 'File Group' => $info->getGroup(), 'File Inode' => $info->getInode(), 'File Link Target' => $info->isLink() ? $info->getLinkTarget() : '-', 'File Name' => $info->getBasename('.' . $info->getExtension()), 'File Name w. Extension' => $info->getFilename(), 'File Owner' => $info->getOwner(), 'File Path' => $info->getPath(), 'Name' => $info->getRealPath(), 'Type' => $info->getType()];
     $aDetails = array_merge($aFileBasicDetails, $this->getFileDetailsRawStatistic($info, $fileGiven));
     ksort($aDetails);
     return $aDetails;
 }
Example #30
0
 /**
  * Reads a file
  *
  * @param string $key
  * @param bool $includeContent
  *
  * @return File|boolean
  */
 public function read($key, $includeContent = true)
 {
     if (!$this->exists($key) || !is_readable($key)) {
         return false;
     }
     $info = new \SplFileInfo($key);
     $file = new File();
     $file->size = $info->getSize();
     $file->name = $info->getFilename();
     if ($includeContent) {
         $file->content = file_get_contents($info->getRealPath());
     }
     $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
     $file->mime = finfo_file($fileInfo, $info->getRealPath());
     finfo_close($fileInfo);
     return $file;
 }