예제 #1
0
 public static function readFile($path)
 {
     $file = new SplFileInfo($path, '', '');
     if (!$file->isFile()) {
         throw new Exception('Invalid file. Fail to get file ' . $path);
     }
     return $file;
 }
예제 #2
0
 /**
  * Parse the contents of the file.
  *
  * Example:
  *
  *     ---
  *     title: Title
  *     date: 2016-07-29
  *     ---
  *     Lorem Ipsum.
  *
  * @throws \RuntimeException
  *
  * @return $this
  */
 public function parse()
 {
     if ($this->file->isFile()) {
         if (!$this->file->isReadable()) {
             throw new \RuntimeException('Cannot read file');
         }
         // parse front matter
         preg_match('/' . self::PATTERN . '/s', $this->file->getContents(), $matches);
         // if not front matter, set body only
         if (!$matches) {
             $this->body = $this->file->getContents();
             return $this;
         }
         $this->frontmatter = trim($matches[1]);
         $this->body = trim($matches[2]);
     }
     return $this;
 }
예제 #3
0
 private function getVersionFromComposerJson($dir)
 {
     $version = '_._._';
     /** @var SplFileInfo $composerFile */
     $composerFile = new SplFileInfo($dir . '/composer.json', '', '');
     if ($composerFile->isFile()) {
         $composerJson = json_decode($composerFile->getContents());
         return $composerJson->version;
     }
     return $version;
 }
예제 #4
0
 /**
  * @param SplFileInfo $file
  *
  * @return string
  */
 public function clean(SplFileInfo $file)
 {
     $name = $file->getFilename();
     if ($file->isFile()) {
         $name = pathinfo($name, PATHINFO_FILENAME);
     }
     $name = str_replace("\t\n\r\v", ' ', $name);
     // remove control characters
     $name = str_replace('_', ' ', $name);
     $name = preg_replace('/\\[[^\\[\\]]*\\]/', ' ', $name);
     // remove [...]
     $name = preg_replace('/\\([^\\(\\)]*\\)/', ' ', $name);
     // remove (...)
     // remove all file meta data
     $reg = sprintf('/[ .,](?:%s)[ .,]/i', implode('|', $this->meta));
     while (preg_match($reg, $name . ' ')) {
         $name = preg_replace($reg, ' ', $name . ' ');
     }
     $name = str_replace('  ', ' ', $name);
     // remove double spaces
     $name = trim($name, ' .,-');
     return $name;
 }
 /**
  * @param string|null $code
  * @param SplFileInfo $file
  * @param string      $suffix
  *
  * @return string|null
  */
 private function determineCode($code, SplFileInfo $file, $suffix)
 {
     if (null !== $code) {
         return $code;
     }
     $candidateFile = new SplFileInfo($file->getPathname() . $suffix, '', '');
     if ($candidateFile->isFile()) {
         return $candidateFile->getContents();
     }
 }
예제 #6
0
 /**
  * Build the site
  */
 public function build()
 {
     $that = $this;
     $this->root = realpath($this->root);
     // First, clean up non-existent files
     if (file_exists($this->outputDir)) {
         $deleteFinder = new Finder();
         $deleteFinder->in($this->outputDir)->filter(function (SplFileInfo $dstFile) {
             // Filter out entries where the source does not exist, or is not the same type
             $srcFile = new SplFileInfo("{$this->root}/{$dstFile->getRelativePathname()}", $dstFile->getRelativePath(), $dstFile->getRelativePathname());
             $old = $dstFile->isDir() && !$srcFile->isDir() || $dstFile->isFile() && !$srcFile->isFile();
             $event = new OldFileEvent($this, $srcFile, $dstFile, $old);
             $this->dispatcher->dispatch(BrancherEvents::OLDFILE, $event);
             return $event->isOld();
         });
         $this->filesystem->remove($deleteFinder);
     }
     // Find all files in root directory
     $renderFinder = new Finder();
     $renderFinder->files()->in(realpath($this->root))->ignoreDotFiles(false);
     array_map([$renderFinder, 'notPath'], array_filter(array_map(function ($exclude) use($that) {
         return $this->filesystem->makePathRelative(realpath($exclude), $that->root);
     }, array_merge($this->excludes, [$this->outputDir]))));
     $this->dispatcher->dispatch(BrancherEvents::SETUP, new SetupEvent($this, $renderFinder));
     // Render every file and dump to output
     $directoryVisited = [];
     /** @var \Symfony\Component\Finder\SplFileInfo $fileInfo */
     foreach ($renderFinder as $fileInfo) {
         $path = $fileInfo->getRelativePath();
         if (!isset($directoryVisited[$path])) {
             $pathObj = new SplFileInfo($fileInfo->getPath(), basename($fileInfo->getRelativePath()), $fileInfo->getRelativePath());
             $event = new DirectoryEnterEvent($this, $pathObj, $this->getSpecialConfig($fileInfo->getPath()));
             $this->dispatcher->dispatch(BrancherEvents::DIRECTORY_ENTER, $event);
             $directoryVisited[$path] = !$event->isShouldSkip();
         }
         if ($directoryVisited[$fileInfo->getRelativePath()] === false) {
             continue;
         }
         if ($fileInfo->getFilename() === $this->specialFile) {
             continue;
         }
         if (substr($this->finfo->file($fileInfo->getPathname()), 0, 4) === 'text') {
             $this->renderFile($fileInfo->getRelativePathname(), $fileInfo->getRelativePathname(), ['path' => $fileInfo->getRelativePathname()]);
         } else {
             // Dump binary files verbatim into output directory
             $this->filesystem->copy($fileInfo->getPathname(), "{$this->outputDir}/{$fileInfo->getRelativePathname()}");
         }
     }
     // Finally, we need to add all remaining templates as resources to Assetic
     // so it will dump the proper files
     /** @var \Twig_Loader_Filesystem $loader */
     $loader = $this->twig->getLoader();
     if ($loader instanceof \Twig_Loader_Filesystem) {
         $resourceFinder = new Finder();
         foreach ($loader->getNamespaces() as $ns) {
             $resourceFinder->in($loader->getPaths($ns));
         }
         /** @var \Symfony\Component\Finder\SplFileInfo $template */
         foreach ($resourceFinder as $template) {
             $this->manager->addResource(new TwigResource($loader, $template->getRelativePathname()), 'twig');
         }
     }
     $this->writer->writeManagerAssets($this->manager);
     $this->dispatcher->dispatch(BrancherEvents::TEARDOWN, new TeardownEvent($this));
 }
 function it_should_filter_by_date(SplFileInfo $file1, SplFileInfo $file2)
 {
     $file1->isFile()->willReturn(true);
     $file2->isFile()->willReturn(true);
     $file1->getRealPath()->willReturn($this->tempFile);
     $file2->getRealPath()->willReturn($this->tempFile);
     $file1->getMTime()->willReturn(strtotime('-4 hours'));
     $file2->getMTime()->willReturn(strtotime('-5 days'));
     $result = $this->date('since yesterday');
     $result->shouldBeAnInstanceOf('GrumPHP\\Collection\\FilesCollection');
     $result->count()->shouldBe(1);
     $files = $result->toArray();
     $files[0]->shouldBe($file1);
 }
예제 #8
0
 /**
  * Move a single file or folder.
  *
  * @param SplFileInfo $file      The file to move.
  *
  * @param string      $targetDir The destination directory.
  *
  * @param bool        $logging   Flag determining if actions shall get logged.
  *
  * @param IOInterface $ioHandler The io handler to log to.
  *
  * @return void
  *
  * @throws \RuntimeException When an unknown file type has been encountered.
  */
 private function moveFile(SplFileInfo $file, $targetDir, $logging, $ioHandler)
 {
     $pathName = $file->getPathname();
     $destinationFile = str_replace($this->tempDir, $targetDir, $pathName);
     // Symlink must(!) be handled first as the isDir() and isFile() checks return true for symlinks.
     if ($file->isLink()) {
         $target = $file->getLinkTarget();
         if ($logging) {
             $ioHandler->write(sprintf('link %s to %s', $target, $destinationFile));
         }
         symlink($target, $destinationFile);
         unlink($pathName);
         return;
     }
     if ($file->isDir()) {
         $permissions = substr(decoct(fileperms($pathName)), 1);
         $this->folders[] = $pathName;
         if (!is_dir($destinationFile)) {
             if ($logging) {
                 $ioHandler->write(sprintf('mkdir %s (permissions: %s)', $pathName, $permissions));
             }
             mkdir($destinationFile, octdec($permissions), true);
         }
         return;
     }
     if ($file->isFile()) {
         $permissions = substr(decoct(fileperms($pathName)), 1);
         if ($logging) {
             $ioHandler->write(sprintf('move %s to %s (permissions: %s)', $pathName, $destinationFile, $permissions));
         }
         copy($pathName, $destinationFile);
         chmod($destinationFile, octdec($permissions));
         unlink($pathName);
         return;
     }
     throw new \RuntimeException(sprintf('Unknown file of type %s encountered for %s', filetype($pathName), $pathName));
 }
 /**
  * Lista carpeta y archivos segun el path ingresado, no recursivo, ordenado por tipo y nombre
  * 
  * @param string $path Ruta de la carpeta o archivo
  * @return array|null Listado de archivos o null si no existe
  */
 public function getAllFiles($path)
 {
     $fullpath = $this->getFullPath() . $path;
     if (file_exists($fullpath)) {
         $file = new \SplFileInfo($fullpath);
         if ($file->isDir()) {
             $r = array();
             // if($path != "/") $r[] = $this->folderParent($path);
             $finder = new Finder();
             $directories = $finder->notName('_thumbs')->notName('web.config')->notName('.htaccess')->depth(0)->sortByType();
             // $directories = $directories->files()->name('*.jpg');
             $directories = $directories->in($fullpath);
             foreach ($directories as $key => $directorie) {
                 $namefile = $directorie->getFilename();
                 if ($directorie->isDir() && $this->validNameFile($namefile, false)) {
                     $t = $this->fileInfo($directorie, $path);
                     if ($t) {
                         $r[] = $t;
                     }
                 } elseif ($directorie->isFile() && $this->validNameFile($namefile)) {
                     $t = $this->fileInfo($directorie, $path);
                     if ($t) {
                         $r[] = $t;
                     }
                 }
             }
             return $r;
         } elseif ($file->isFile()) {
             $t = $this->fileInfo($file, $path);
             if ($t) {
                 return $t;
             } else {
                 $result = array("query" => "BE_GETFILEALL_NOT_LEIBLE", "params" => array());
                 $this->setInfo(array("msg" => $result));
                 if ($this->config['debug']) {
                     $this->_log(__METHOD__ . " - Archivo no leible - {$fullpath}");
                 }
                 return;
             }
         } elseif ($file->isLink()) {
             $result = array("query" => "BE_GETFILEALL_NOT_PERMITIDO", "params" => array());
             $this->setInfo(array("msg" => $result));
             if ($this->config['debug']) {
                 $this->_log(__METHOD__ . " - path desconocido - {$fullpath}");
             }
             return;
         }
     } else {
         $result = array("query" => "BE_GETFILEALL_NOT_EXISTED", "params" => array());
         $this->setInfo(array("msg" => $result));
         if ($this->config['debug']) {
             $this->_log(__METHOD__ . " - No existe el archivo - {$fullpath}");
         }
         return;
     }
 }
 public function isFile()
 {
     return $this->fileInfo->isFile();
 }