Beispiel #1
0
 /**
  * Write content into file. If file exists it will be overwritten.
  *
  * @param $path
  * @param $contents
  */
 public function write($path, $contents)
 {
     if ($this->filesystem->has($path)) {
         $this->remove($path);
     }
     $this->filesystem->write($path, $contents);
 }
Beispiel #2
0
 protected function write($data)
 {
     $destination = $this->composer->getClassPath($this->data['name']);
     if ($this->force && $this->external->has($destination)) {
         $this->external->delete($destination);
     }
     return $this->external->write($destination, $data);
 }
Beispiel #3
0
 protected function installParts()
 {
     $config = new \stdClass();
     foreach ($this->parts as $part) {
         $part->setupPackage($config, $this->filesystem);
     }
     $this->filesystem->write('composer.json', json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
 }
Beispiel #4
0
 /**
  * @return false|string
  */
 private function loadFile()
 {
     if (!$this->filesystem->has($this->getFile())) {
         $this->filesystem->write($this->getFile(), '');
     }
     if (!$this->sites) {
         $this->sites = $this->filesystem->read($this->file);
     }
     return $this->sites;
 }
 /**
  * @param File $file
  * @param Version $version
  * @param VersionProvider $versionProvider
  * @param Linker $linker
  * @return bool
  */
 public function publish(File $file, Version $version, VersionProvider $versionProvider, Linker $linker)
 {
     $path = $linker->getLink($file, $version, $versionProvider->getExtension($file, $version));
     $tmp = $this->storage->retrieveVersion($versionProvider->getApplicableVersionable($file), $version);
     if ($this->filesystem->has($path)) {
         return false;
     }
     $this->filesystem->write($path, file_get_contents($tmp), ['visibility' => AdapterInterface::VISIBILITY_PUBLIC]);
     return true;
 }
 /**
  * @param string $content
  * @param string $path
  * @return bool
  * @throws \InvalidArgumentException
  * @throws \League\Flysystem\FileNotFoundException
  */
 public function publish($content, $path = '')
 {
     if (empty($path)) {
         throw new \InvalidArgumentException('Path is mandatory!');
     }
     $config = new Config();
     try {
         return $this->storage->write($path, $content, $config);
     } catch (FileExistsException $e) {
         return $this->storage->update($path, $content, $config);
     }
 }
Beispiel #7
0
 public function convert($filePathIn, $filePathOut)
 {
     $replace = [];
     $replace['js_app'] = file_get_contents(__DIR__ . "/../../templates/{$this->usedTemplate}/" . "{$this->usedTemplate}.js");
     $replace['js_bootstrap'] = file_get_contents(self::PATH_DIST_BOOTSTRAP_JS);
     $replace['css_app'] = file_get_contents(__DIR__ . "/../../templates/{$this->usedTemplate}/" . "{$this->usedTemplate}.css");
     $replace['css_bootstrap'] = file_get_contents(self::PATH_DIST_BOOTSTRAP_CSS);
     $replace['content'] = $this->mdParser->parse(file_get_contents($filePathIn));
     $output['html'] = $this->latte->renderToString(__DIR__ . "/../../templates/{$this->usedTemplate}/" . "{$this->usedTemplate}.latte", $replace);
     $output['pdf'] = "@todo :)";
     $this->fs->write("{$filePathOut}.html", $output['html']);
     $this->fs->write("{$filePathOut}.pdf", $output['pdf']);
 }
 /**
  * @return bool
  */
 private function writeToFile()
 {
     $this->filesystem->write($this->file, $this->template);
     $this->out->writeln("Written endpoint wrapper to :" . $this->filesystem->get($this->file)->getPath());
     $this->out->writeln("Class " . $this->className . " is generated");
     return $this;
 }
Beispiel #9
0
    public function run()
    {
        $log = new Stream('php://stdout');
        /** @var Config $config */
        $config = Di::getDefault()->getShared('config');
        $expireDate = new DateTime('now', new DateTimeZone('UTC'));
        $expireDate->modify('+1 month');
        $baseUrl = rtrim($config->get('site')->url, '/');
        $content = <<<EOL
User-agent: *
Allow: /
Sitemap: {$baseUrl}/sitemap.xml
EOL;
        $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
        $filesystem = new Filesystem($adapter);
        if ($filesystem->has('robots.txt')) {
            $result = $filesystem->update('robots.txt', $content);
        } else {
            $result = $filesystem->write('robots.txt', $content);
        }
        if ($result) {
            $log->info('The robots.txt was successfully updated');
        } else {
            $log->error('Failed to update the robots.txt file');
        }
    }
Beispiel #10
0
 public function write($path, $contents, array $config = [])
 {
     if (parent::write($path, $contents, $config)) {
         return $this->getAdapter()->getModel();
     } else {
         return false;
     }
 }
 /**
  * Write a new file.
  *
  * @param string $path     The path of the new file.
  * @param string $contents The file contents.
  * @param array  $config   An optional configuration array.
  *
  * @throws FileExistsException
  *
  * @return bool True on success, false on failure.
  */
 public function write($path, $contents, array $config = [])
 {
     $result = parent::write($path, $contents, $config);
     if ($result && ($resource = $this->get($path))) {
         return $this->dispatch(new SyncFile($resource));
     }
     return $result;
 }
Beispiel #12
0
 /**
  * Write a new file from File.
  *
  * @param File $file File object
  *
  * @throws FileExistsException
  *
  * @return bool True on success, false on failure.
  */
 public function writeFile(File $file)
 {
     try {
         return $this->filesystem->write($file->getDirectories() . $file->getFileName(), $file->getResource(), []);
     } catch (FlysystemFileExistsException $e) {
         FileExistsException::fileExists();
     }
 }
 /**
  * @inheritdoc
  */
 protected function _mkfile($path, $name)
 {
     $path = $this->_joinPath($path, $name);
     if ($this->fs->write($path, '')) {
         return $path;
     }
     return false;
 }
Beispiel #14
0
 protected function copyTo($file, Filesystem $target, $targetName = null, Closure $handler = null)
 {
     $targetName = $targetName ?: basename($file);
     $content = file_get_contents($file);
     if ($handler) {
         $content = $handler($content);
     }
     $target->write($targetName, $content);
 }
 /**
  * Create skip file to lessons
  */
 public function writeSkipSeries()
 {
     $file = SERIES_FOLDER . '/.skip';
     $series = serialize($this->getSeries());
     if ($this->system->has($file)) {
         $this->system->delete($file);
     }
     $this->system->write($file, $series);
 }
 /**
  * Set string to cache in filesystem.
  *
  * @param  string $key
  * @param  string $data
  */
 public function set($key, $data)
 {
     if (!is_string($key) || !is_string($data)) {
         return;
     }
     $file = $this->get_file_name($key);
     $data = $this->minify($data);
     $this->filesystem->write($file, $data);
 }
Beispiel #17
0
 /**
  * @return  self
  */
 public function convert($filePathIn, $filePathOut, $formats = ['html', 'pdf'])
 {
     $output = ['html' => '', 'pdf' => ''];
     $replace = ['content' => '', 'js' => '', 'css' => ''];
     try {
         $tpl = TemplatesRegistry::get($this->usedTemplate);
         foreach (['js', 'css'] as $type) {
             foreach ($tpl[$type] as $file) {
                 if (!is_readable($file)) {
                     throw new \Exception("Cannot load file {$file}.");
                 }
                 $file = file_get_contents($file);
                 $replace[$type] .= $file . "\n";
             }
         }
         if (file_exists("{$filePathOut}.html")) {
             unlink("{$filePathOut}.html");
         }
         $replace['content'] = $this->mdParser->parse(file_get_contents($filePathIn));
         $output['html'] = $this->latte->renderToString($tpl['layout'], $replace);
         $this->fs->write("{$filePathOut}.html", $output['html']);
         if (in_array('pdf', $formats)) {
             try {
                 $html2pdf = new \HTML2PDF('P', 'A4', 'cs');
                 $html2pdf->setDefaultFont('dejavusans');
                 //$html2pdf->addFont('dejavusans');
                 $html2pdf->pdf->SetDisplayMode('real');
                 $output['html'] = str_replace('\\xe28087', "&#160;&#160;", $output['html']);
                 $html2pdf->writeHTML($output['html']);
                 $pdf = $html2pdf->Output("{$filePathOut}.pdf", 'S');
                 $this->fs->write("{$filePathOut}.pdf", $pdf);
             } catch (Html2PdfException $e) {
                 $formatter = new ExceptionFormatter($e);
                 echo "PDF: " . $formatter->getHtmlMessage();
             }
         }
         if (!in_array('html', $formats)) {
             //unlink("{$filePathOut}.html");
         }
     } catch (\InvalidArgumentException $e) {
         echo $e->getMessage(), "\n";
     }
     return $this;
 }
 /**
  * Uploads raw contents to the service.
  *
  * @param string $contents
  * @return array    The meta of the file.
  */
 public function uploadContents($name, $contents)
 {
     // raw contents not allowed
     $tmpFilesystem = new Filesystem(new Local(storage_path('tmp/')));
     $tmpFilesystem->write($name, $contents);
     $meta = Uploader::upload(storage_path('tmp/' . $name));
     // force secure url
     $meta['url'] = $meta['secure_url'];
     return $meta;
 }
Beispiel #19
0
 /**
  * Obtain a lock for a given key.
  * It'll try to get a lock for a couple of times, but ultimately give up if
  * no lock can be obtained in a reasonable time.
  *
  * @param string $key
  *
  * @return bool
  */
 protected function lock($key)
 {
     $path = $key . '.lock';
     for ($i = 0; $i < 25; ++$i) {
         try {
             $this->filesystem->write($path, '');
             return true;
         } catch (FileExistsException $e) {
             usleep(200);
         }
     }
     return false;
 }
Beispiel #20
0
 /**
  * @inheritdoc
  */
 public function write($path, $contents, array $config = [])
 {
     $innerPath = $this->getInnerPath($path);
     try {
         $return = $this->fileSystem->write($innerPath, $contents, $config);
     } catch (FileExistsException $e) {
         throw $this->exceptionWrapper($e, $path);
     }
     if ($return !== false) {
         $this->invokePlugin("addPathToIndex", [$path, $innerPath], $this);
     }
     return $return;
 }
Beispiel #21
0
 public function run()
 {
     $log = new Stream('php://stdout');
     /** @var Config $config */
     $config = Di::getDefault()->getShared('config');
     $expireDate = new DateTime('now', new DateTimeZone('UTC'));
     $expireDate->modify('+1 day');
     $sitemap = new DOMDocument("1.0", "UTF-8");
     $sitemap->formatOutput = true;
     $urlset = $sitemap->createElement('urlset');
     $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $baseUrl = $config->get('site')->url;
     $url = $sitemap->createElement('url');
     $url->appendChild($sitemap->createElement('loc', $baseUrl));
     $url->appendChild($sitemap->createElement('changefreq', 'daily'));
     $url->appendChild($sitemap->createElement('priority', '1.0'));
     $urlset->appendChild($url);
     $karmaSql = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies';
     $parametersPosts = ['conditions' => 'deleted != 1', 'columns' => "id, slug, modified_at, {$karmaSql} AS karma", 'order' => 'karma DESC'];
     $posts = Posts::find($parametersPosts);
     $parametersKarma = ['column' => $karmaSql, 'conditions' => 'deleted != 1'];
     $karma = Posts::maximum($parametersKarma);
     $modifiedAt = new DateTime('now', new DateTimeZone('UTC'));
     foreach ($posts as $post) {
         $modifiedAt->setTimestamp($post->modified_at);
         $postKarma = $post->karma / ($karma + 100);
         $url = $sitemap->createElement('url');
         $href = trim($baseUrl, '/') . '/discussion/' . $post->id . '/' . $post->slug;
         $url->appendChild($sitemap->createElement('loc', $href));
         $valuePriority = $postKarma > 0.7 ? sprintf("%0.1f", $postKarma) : sprintf("%0.1f", $postKarma + 0.25);
         $url->appendChild($sitemap->createElement('priority', $valuePriority));
         $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\\TH:i:s\\Z')));
         $urlset->appendChild($url);
     }
     $sitemap->appendChild($urlset);
     $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
     $filesystem = new Filesystem($adapter);
     if ($filesystem->has('sitemap.xml')) {
         $result = $filesystem->update('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     } else {
         $result = $filesystem->write('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     }
     if ($result) {
         $log->info('The sitemap.xml was successfully updated');
     } else {
         $log->error('Failed to update the sitemap.xml file');
     }
 }
 /**
  * Handle the command
  *
  * @param $command
  * @return mixed
  */
 public function handle($command)
 {
     $client = S3Client::factory(array('key' => $this->config->get('services.s3.key'), 'secret' => $this->config->get('services.s3.secret')));
     /*
      * Upload image to S3
      */
     $filesystem = new Flysystem(new Adapter($client, $this->config->get('sightseeing.s3-bucket')));
     $extension = $this->filesystem->extension($command->image->getClientOriginalName());
     $filename = sha1(time() . time()) . ".{$extension}";
     $filesystem->write($filename, file_get_contents($command->image), ['visibility' => 'public']);
     /*
      * Create record on the database
      */
     $this->sightRepository->addImageById($command->id, $filename);
 }
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return null
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $transformer = new DashToCamelCase();
     $filter = new Alpha();
     $name = $input->getArgument('name');
     $className = $filter->filter($transformer->filter(ucfirst($name)));
     $description = $input->getArgument('description');
     $filesystem = new Filesystem(new Adapter(dirname(dirname(dirname(dirname(dirname(__DIR__)))))));
     $template = $filesystem->read('vendor/middleout/mdo-bundle-zf2-cli/templates/Command/TemplateCommand.php');
     $template = str_replace(['TemplateCommandName', 'TemplateCommandDescription', 'TemplateCommandLiteralName'], [$className . 'Command', $description, $name], $template);
     $filesystem->write('module/Cli/src/Command/' . $className . 'Command.php', $template);
     $output->writeln('');
     $output->writeln('Created command succesfully in path "module/Cli/src/Command/' . $className . 'Command.php"');
     $output->writeln('');
 }
Beispiel #24
0
 protected function _createFileOnDir(Local $adapter, $outFile)
 {
     $filesystem = new Filesystem($adapter);
     $dir = pathinfo($adapter->getPathPrefix() . $outFile, PATHINFO_DIRNAME) . '/';
     if (!is_dir($dir)) {
         $this->logger->info('Creo directory mancante: ' . $dir);
         mkdir($dir, 0700, true);
     }
     if ($filesystem->has($outFile)) {
         $filesystem->put($outFile, (string) $this->currentFile);
     } else {
         $filesystem->write($outFile, (string) $this->currentFile);
     }
     return $outFile;
     //$io->text('Outfile: '.$outFile);
 }
Beispiel #25
0
 /**
  * Save new FileName based on source file and list of options
  *
  * @param $sourceFile
  * @param $newFileName
  * @param $options
  * @throws \Exception
  */
 public function saveNewFile($sourceFile, $newFileName, $options)
 {
     $newFilePath = TMP_DIR . $newFileName;
     $tmpFile = $this->saveToTemporaryFile($sourceFile);
     $commandStr = $this->generateCmdString($newFilePath, $tmpFile, $options);
     exec($commandStr, $output, $code);
     if (count($output) === 0) {
         $output = $code;
     } else {
         $output = implode(PHP_EOL, $output);
     }
     if ($code !== 0) {
         throw new \Exception($output . ' Command line: ' . $commandStr);
     }
     $this->filesystem->write($newFileName, stream_get_contents(fopen($newFilePath, 'r')));
     unlink($tmpFile);
     unlink($newFilePath);
 }
Beispiel #26
0
 /**
  * Renders the specified templates.
  * 
  * @param  \League\Flysystem\Filesystem $filesystem
  * @param  \Twig_Environment $renderer
  * @param  array $templates
  * @param  array $data
  * @return void
  */
 public static function render(Filesystem $filesystem, \Twig_Environment $renderer, array $templates = [], array $data = [])
 {
     $slash = DIRECTORY_SEPARATOR;
     foreach ($templates as $template) {
         $sourceFile = str_replace($data['directory'] . $slash, '', $template);
         if ($filesystem->has($sourceFile)) {
             $filesystem->delete($sourceFile);
         }
         if (strpos($sourceFile, '.twig') === false) {
             $contents = $renderer->render('Application' . $slash . $sourceFile, $data);
         } else {
             $contents = file_get_contents($data['directory'] . $slash . $sourceFile);
             $contents = str_replace('{application}', $data['application']->name, $contents);
         }
         if (strpos($sourceFile, '.file') !== false) {
             $sourceFile = str_replace('.file', '', $sourceFile);
         }
         $filesystem->write($sourceFile, $contents);
     }
 }
require_once __DIR__ . '/../vendor/autoload.php';
use League\Flysystem\Filesystem;
use League\Flysystem\Memory\MemoryAdapter as Adapter;
use Flyfinder\Finder;
use Flyfinder\Path;
use Flyfinder\Specification\IsHidden;
use Flyfinder\Specification\HasExtension;
use Flyfinder\Specification\InPath;
/*
 * First create a new Filesystem and add the FlySystem plugin
 * In this example we are using a filesystem with the memory adapter
 */
$filesystem = new Filesystem(new Adapter());
$filesystem->addPlugin(new Finder());
// Create some demo files
$filesystem->write('test.txt', 'test');
$filesystem->write('.hiddendir/.test.txt', 'test');
$filesystem->write('.hiddendir/found.txt', 'test');
$filesystem->write('.hiddendir/normaldir/example.txt', 'test');
/*
 * In order to tell FlyFinder what to find, you need to give it a specification
 * In this example the specification will be satisfied by *.txt files
 * within the .hidden directory and its subdirectories that are not hidden
 */
$isHidden = new IsHidden();
$hasExtension = new HasExtension(['txt']);
$inPath = new InPath(new Path('.hiddendir'));
$specification = $inPath->andSpecification($hasExtension)->andSpecification($isHidden->notSpecification());
//FlyFinder will yield a generator object with the files that are found
$generator = $filesystem->find($specification);
$result = [];
 public function saveAsZip($identifier)
 {
     //initialize variables
     $archives = new Filesystem(new Local($this->container_path));
     $local = new Filesystem(new Local($this->container_path . $identifier));
     $zip = new Filesystem(new ZipArchiveAdapter($this->archives_path . time() . '-' . $identifier . '.zip'));
     //make sure the directory exists
     $archives->createDir('archives');
     //list dir for CMS
     $contents = $local->listContents('', true);
     foreach ($contents as $info) {
         if ($info['type'] === 'dir') {
             continue;
         }
         $zip->write($info['path'], $local->read($info['path']));
     }
     // This will trigger saving the zip.
     $zip = null;
     return true;
 }
Beispiel #29
0
 public function testNoop()
 {
     $filesystem = new Filesystem(new Adapter\Local(__DIR__ . '/files'), new Cache\Noop());
     $filesystem->write('test.txt', 'contents');
     $this->assertTrue($filesystem->has('test.txt'));
     $this->assertInternalType('array', $filesystem->listContents());
     $this->assertInternalType('array', $filesystem->listContents('', true));
     $cache = $filesystem->getCache();
     $cache->setComplete('', false);
     $cache->flush();
     $cache->autosave();
     $this->assertFalse($cache->isComplete('', false));
     $this->assertFalse($cache->read('something'));
     $this->assertFalse($cache->getMetadata('something'));
     $this->assertFalse($cache->getMimetype('something'));
     $this->assertFalse($cache->getSize('something'));
     $this->assertFalse($cache->getTimestamp('something'));
     $this->assertFalse($cache->getVisibility('something'));
     $this->assertFalse($cache->listContents('', false));
     $this->assertFalse($cache->rename('', ''));
     $this->assertFalse($cache->copy('', ''));
     $filesystem->delete('test.txt');
     $this->assertEquals(array(), $cache->storeContents('unknwon', array(array('path' => 'some/file.txt')), false));
 }
Beispiel #30
0
 /**
  * {@inheritDoc}
  */
 public function write($path, $contents, array $config = [])
 {
     $path = $this->prepareFileLocation($path);
     parent::write($path, $contents, $config);
     return $this->get($path);
 }