Exemplo n.º 1
1
 /**
  * {@inheritdoc}
  */
 public function saveFile(UploadedFile $uploadedFile, $fileName)
 {
     $stream = fopen($uploadedFile->getRealPath(), 'r+');
     $result = $this->filesystem->writeStream($this->getMediaBasePath() . '/' . $fileName . '.' . $uploadedFile->guessClientExtension(), $stream);
     fclose($stream);
     return $result;
 }
Exemplo n.º 2
0
 /**
  * read all metadata from module file.
  * @param type $module_system_name
  * @return type
  */
 public function readModuleMetadata($module_system_name)
 {
     $adapter = new Local(MODULE_PATH);
     $filesystem = new Filesystem($adapter);
     unset($adapter);
     $output = [];
     if ($filesystem->has($module_system_name . DS . $module_system_name . '.php')) {
         $content = $filesystem->read($module_system_name . DS . $module_system_name . '.php');
         preg_match_all('|([a-zA-Z0-9-_ ]+):(.*)$|mi', $content, $matches, PREG_PATTERN_ORDER);
         unset($content);
         if (isset($matches) && is_array($matches) && array_key_exists(1, $matches) && array_key_exists(2, $matches) && is_array($matches[1]) && is_array($matches[2])) {
             foreach ($matches[1] as $key => $item) {
                 if (!is_array($item) && array_key_exists($key, $matches[2]) && !is_array($matches[2][$key])) {
                     $output[trim($item)] = trim($matches[2][$key]);
                 }
             }
         }
     }
     // validate available metadata
     foreach ($this->available_metadata as $meta_name) {
         if (!array_key_exists($meta_name, $output)) {
             $output[$meta_name] = '';
         }
     }
     unset($filesystem, $item, $key, $matches, $meta_name);
     return $output;
 }
 public function testDeleteMockResourceExistsSizes()
 {
     $resourceDO = $this->getResourceDOMock();
     $this->filesystem->put($resourceDO->getFilePath(), '');
     $resourceDOSize10x11 = $this->getResourceDOMock();
     $resourceDOSize10x11->setWidth(10);
     $resourceDOSize10x11->setHeight(11);
     $this->filesystem->put($resourceDOSize10x11->getFilePath(), '');
     $resourceDOSize20x21 = $this->getResourceDOMock();
     $resourceDOSize20x21->setWidth(20);
     $resourceDOSize20x21->setHeight(21);
     $this->filesystem->put($resourceDOSize20x21->getFilePath(), '');
     $yetAnotherWrongDO = clone $resourceDO;
     $yetAnotherWrongDO->setWidth(998);
     $yetAnotherWrongDO->setHeight(999);
     $this->wrongFiles->create($resourceDO, 'Wrong1');
     $this->wrongFiles->create($resourceDOSize10x11, 'Wrong2');
     $this->wrongFiles->create($resourceDOSize20x21, 'Wrong3');
     $this->wrongFiles->create($yetAnotherWrongDO, 'Wrong4');
     $modelFiles = $this->filesystem->listContents('/', true);
     // Make the expected model looks like filesystem after the command execution
     // With this model we will be sure that other files have not been deleted
     unset($modelFiles[56], $modelFiles[57]);
     $modelFiles[55] = ['type' => 'dir', 'path' => 'testBase/png/def/def/0/c9f/20x21', 'dirname' => 'testBase/png/def/def/0/c9f', 'basename' => '20x21', 'filename' => '20x21'];
     $command = $this->getCommand($resourceDO);
     $result = $command();
     $this->assertTrue($result);
     $this->assertFalse($this->filesystem->has($resourceDOSize10x11->getFilePath()));
     $this->assertFalse($this->filesystem->has($resourceDOSize20x21->getFilePath()));
     $result = $this->filesystem->listContents('/', true);
     $this->assertEquals($modelFiles, $result);
 }
Exemplo n.º 4
0
 function it_should_execute_the_transfer_file_command(Filesystem $source, Filesystem $destination)
 {
     $source->readStream('source')->willReturn('data');
     $destination->writeStream('destination', 'data')->shouldBeCalled();
     $this->beConstructedWith($source, 'source', $destination, 'destination');
     $this->execute();
 }
 function it_throws_an_exception_when_configuration_cannot_be_written(Flysystem $filesystem, Renderer $renderer, Configuration $configuration)
 {
     $renderer->render($configuration)->willReturn('contents');
     $filesystem->put('file', 'contents')->willReturn(false);
     $this->beConstructedWith($filesystem, 'file', $renderer);
     $this->shouldThrow('Indigo\\Supervisor\\Exception\\WrittingFailed')->duringWrite($configuration);
 }
Exemplo n.º 6
0
 public function testHas()
 {
     $mock = $this->getClient();
     $mock->shouldReceive('propFind')->once()->andReturn(array('{DAV:}getcontentlength' => 20));
     $adapter = new Filesystem(new Adapter($mock));
     $this->assertTrue($adapter->has('something'));
 }
Exemplo n.º 7
0
 /**
  * read all metadata from theme file.
  * @param type $theme_system_name
  * @return type
  */
 public function readThemeMetadata($theme_system_name)
 {
     // get theme config
     $Config = new \System\Libraries\Config();
     $Config->load('theme');
     $theme_dir = $Config->get('theme_dir', 'theme');
     unset($Config);
     $adapter = new Local($theme_dir);
     $filesystem = new Filesystem($adapter);
     unset($adapter, $theme_dir);
     $output = [];
     if ($filesystem->has($theme_system_name . DS . $theme_system_name . '.php')) {
         $content = $filesystem->read($theme_system_name . DS . $theme_system_name . '.php');
         preg_match_all('|([a-zA-Z0-9-_ ]+):(.*)$|mi', $content, $matches, PREG_PATTERN_ORDER);
         unset($content);
         if (isset($matches) && is_array($matches) && array_key_exists(1, $matches) && array_key_exists(2, $matches) && is_array($matches[1]) && is_array($matches[2])) {
             foreach ($matches[1] as $key => $item) {
                 if (!is_array($item) && array_key_exists($key, $matches[2]) && !is_array($matches[2][$key])) {
                     $output[trim($item)] = trim($matches[2][$key]);
                 }
             }
         }
     }
     // validate available metadata
     foreach ($this->available_metadata as $meta_name) {
         if (!array_key_exists($meta_name, $output)) {
             $output[$meta_name] = '';
         }
     }
     unset($filesystem, $item, $key, $matches, $meta_name);
     return $output;
 }
 public function system()
 {
     $adapter = new Local(__DIR__ . '/../../storage/');
     $filesystem = new Filesystem($adapter);
     $filesystem->createDir($this->getZipName());
     return $filesystem;
 }
Exemplo n.º 9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument("file");
     $list = array_filter($this->filesystem->listContents($file, true), function ($file) {
         return isset($file['type']) and ($file['type'] === "file" and isset($file['extension']) and $file['extension'] === "php");
     });
     // If the file argument is not directory, the listContents will return empty array.
     // In this case the user has specified a file
     if (empty($list)) {
         $list = [["path" => $this->filesystem->get($file)->getPath()]];
     }
     $dump = array_map(function ($file) use($output) {
         $output->writeln("Indexing " . $file['path'] . "...");
         return Indexer::index($this->filesystem->get($file['path']));
     }, $list);
     $table = new Table($output);
     $outputs = [];
     foreach ($dump as $a) {
         foreach ($a["functions"] as $val) {
             $outputs[] = [$val['file']->getPath(), $val['function'], implode(", ", array_map(function ($param) {
                 return implode('|', $param['type']) . " " . $param['name'];
             }, $val['arguments'])), implode(", ", $val['return']), (string) $val['scope']];
         }
     }
     $output->writeln("Indexing complete!");
     $output->writeln("Scanned " . count($list) . " files.");
     $output->writeln("Detected " . count($outputs) . " functions.");
     $output->writeln("Rendering Table...");
     $table->setHeaders(['File', 'Function', 'Arguments', 'Return', 'Scope'])->setRows($outputs);
     $table->render();
 }
Exemplo n.º 10
0
 /**
  * get the languages configuration file path.<br>
  * the languages are store in db. use this class/method to generate them into a file and get the file path that were generated.
  * 
  * @return string return languages configuration file path.
  */
 public function getConfigFile()
 {
     $adapter = new Local($this->language_config_folder);
     $filesystem = new Filesystem($adapter);
     unset($adapter);
     if ($filesystem->has($this->language_db_file)) {
         $lang_file_ts = $filesystem->getTimestamp($this->language_db_file);
         $day_old = (time() - $lang_file_ts) / 60 / 60 / 24;
         if ($day_old > 30) {
             // older than 30 days, rebuild languages.
             $build_result = $this->buildConfigFile();
         }
         unset($day_old, $filesystem, $lang_file_ts);
         if (isset($build_result) && $build_result !== true) {
             \System\Libraries\Log::write('LanguagesDb', 'notice', 'Could not generate the languages from db from getConfigFile method.');
         }
         return $this->language_config_folder . DS . $this->language_db_file;
     } elseif ($this->buildConfigFile() === true) {
         // never build the language configuration file before, build it.
         unset($filesystem);
         return $this->language_config_folder . DS . $this->language_db_file;
     } else {
         return null;
     }
 }
Exemplo n.º 11
0
 /**
  * Return admin assets
  * @param Response $response
  * @param $asset
  * @return Response|static
  * @throws FileNotFoundException
  */
 public function assets(Response $response, $asset)
 {
     $filesystem = new Filesystem(new Adapter(FS2ADMIN));
     $expires = 8640000;
     try {
         // generate cache data
         $timestamp_string = gmdate('D, d M Y H:i:s ', $filesystem->getTimestamp($asset)) . 'GMT';
         $etag = md5($filesystem->read($asset));
         $mime_type = $filesystem->getMimetype($asset);
         if (0 !== strpos($mime_type, 'image')) {
             $mime_type = 'text/css';
         }
         $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
         $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
         if (($if_none_match && $if_none_match == "\"{$etag}\"" || !$if_none_match) && ($if_modified_since && $if_modified_since == $timestamp_string)) {
             return $response->withStatus('304');
         } else {
             $response = $response->withHeader('Last-Modified', $timestamp_string)->withHeader('ETag', "\"{$etag}\"");
         }
         // send out content type, expire time and the file
         $response->getBody()->write($filesystem->read($asset));
         return $response->withHeader('Expires', gmdate('D, d M Y H:i:s ', time() + $expires) . 'GMT')->withHeader('Content-Type', $mime_type)->withHeader('Pragma', 'cache')->withHeader('Cache-Control', 'cache');
     } catch (FileNotFoundException $e) {
         throw $e;
     }
 }
 function it_returns_flat_data_with_media($channelManager, Filesystem $filesystem, ChannelInterface $channel, LocaleInterface $locale, ProductInterface $product, FileInfoInterface $media1, FileInfoInterface $media2, ProductValueInterface $value1, ProductValueInterface $value2, AttributeInterface $attribute, ProductValueInterface $identifierValue, AttributeInterface $identifierAttribute, $serializer, $productBuilder)
 {
     $localeCodes = ['en_US'];
     $channel->getLocales()->willReturn(new ArrayCollection([$locale]));
     $channel->getLocaleCodes()->willReturn($localeCodes);
     $productBuilder->addMissingProductValues($product, [$channel], [$locale])->shouldBeCalled();
     $media1->getKey()->willReturn('key/to/media1.jpg');
     $media2->getKey()->willReturn('key/to/media2.jpg');
     $value1->getAttribute()->willReturn($attribute);
     $value1->getMedia()->willReturn($media1);
     $value2->getAttribute()->willReturn($attribute);
     $value2->getMedia()->willReturn($media2);
     $attribute->getAttributeType()->willReturn('pim_catalog_image');
     $product->getValues()->willReturn([$value1, $value2, $identifierValue]);
     $identifierValue->getAttribute()->willReturn($identifierAttribute);
     $identifierAttribute->getAttributeType()->willReturn('pim_catalog_identifier');
     $product->getIdentifier()->willReturn($identifierValue);
     $identifierValue->getData()->willReturn('data');
     $filesystem->has('key/to/media1.jpg')->willReturn(true);
     $filesystem->has('key/to/media2.jpg')->willReturn(true);
     $serializer->normalize($media1, 'flat', ['field_name' => 'media', 'prepare_copy' => true, 'value' => $value1])->willReturn(['normalized_media1']);
     $serializer->normalize($media2, 'flat', ['field_name' => 'media', 'prepare_copy' => true, 'value' => $value2])->willReturn(['normalized_media2']);
     $serializer->normalize($product, 'flat', ['scopeCode' => 'foobar', 'localeCodes' => $localeCodes, 'decimal_separator' => '.', 'date_format' => 'yyyy-MM-dd'])->willReturn(['normalized_product']);
     $channelManager->getChannelByCode('foobar')->willReturn($channel);
     $this->setChannel('foobar');
     $this->process($product)->shouldReturn(['media' => [['normalized_media1'], ['normalized_media2']], 'product' => ['normalized_product']]);
 }
Exemplo n.º 13
0
 public function generate()
 {
     if (PHP_SAPI != 'cli') {
         throw new \Exception("This script only can be used in CLI");
     }
     $config = $this->config->get('database');
     system(sprintf('/usr/bin/mysqldump -u %s -h %s -p%s -r /tmp/phosphorum.sql %s', $config->username, $config->host, $config->password, $config->dbname));
     system('bzip2 -f /tmp/phosphorum.sql');
     $config = $this->config->get('dropbox');
     if (!$config instanceof Config) {
         throw new \Exception("Unable to retrieve Dropbox credentials. Please check Forum Configuration");
     }
     if (!$config->get('appSecret') || !$config->get('accessToken')) {
         throw new \Exception("Please provide correct 'appSecret' and 'accessToken' config values");
     }
     $sourcePath = '/tmp/phosphorum.sql.bz2';
     if (!file_exists($sourcePath)) {
         throw new \Exception("Backup could not be created");
     }
     $client = new Client($config->get('accessToken'), $config->get('appSecret'));
     $adapter = new DropboxAdapter($client, $config->get('prefix', null));
     $filesystem = new Filesystem($adapter);
     $dropboxPath = '/phosphorum.sql.bz2';
     if ($filesystem->has($dropboxPath)) {
         $filesystem->delete($dropboxPath);
     }
     $fp = fopen($sourcePath, "rb");
     $filesystem->putStream($dropboxPath, $fp);
     fclose($fp);
     @unlink($sourcePath);
 }
Exemplo n.º 14
0
 /**
  * Start the site Scraping process.
  *
  * @param string                  $url
  * @param \GuzzleHttp\Psr7\Stream $body
  *
  * @return void
  */
 protected function writePage($url, $body)
 {
     $page = $this->getPage($url);
     $body = str_replace($this->localSite, $this->remo, "{$body}");
     $write = $this->fs->put($page, $body);
     return $write;
 }
 public function build()
 {
     \yii\base\Event::on(\denoll\filekit\Storage::className(), \denoll\filekit\Storage::EVENT_BEFORE_SAVE, function ($event) {
         /** @var \denoll\filekit\Storage $storage */
         $storage = $event->sender;
         if (!$storage->getFilesystem()->has('.dirindex')) {
             $storage->getFilesystem()->write('.dirindex', 1);
             $dirindex = 1;
         } else {
             $dirindex = $storage->getFilesystem()->read('.dirindex');
         }
         if ($storage->maxDirFiles !== -1) {
             if ($storage->getFilesystem()->has($dirindex)) {
                 $filesCount = count($storage->getFilesystem()->listContents($dirindex));
                 if ($filesCount > $storage->maxDirFiles) {
                     $dirindex++;
                     $storage->getFilesystem()->createDir($dirindex);
                 }
             } else {
                 $storage->getFilesystem()->createDir($dirindex);
             }
         }
     });
     $client = new \Sabre\DAV\Client(['baseUri' => 'https://webdav.yandex.ru']);
     $client->addCurlSetting(CURLOPT_SSL_VERIFYPEER, false);
     $client->addCurlSetting(CURLOPT_HTTPHEADER, ['Authorization: OAuth TOKENTOKENTOKEN', 'Accept: */*', 'Host: webdav.yandex.ru']);
     $adapter = new WebDAVAdapter($client, '/');
     $flysystem = new Filesystem($adapter);
     if (!$flysystem->has($this->pathPrefix)) {
         $flysystem->createDir($this->pathPrefix);
     }
     $adapter->setPathPrefix($this->pathPrefix);
     return $flysystem;
 }
Exemplo n.º 16
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');
        }
    }
Exemplo n.º 17
0
 protected function handleField(Request $request, $item, array $fields, $groupName, $fieldName)
 {
     $modelFolder = $this->slug . DIRECTORY_SEPARATOR;
     $basePath = base_path(DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . config('anavel-crud.uploads_path'));
     $modelPath = $basePath . $modelFolder;
     $skip = null;
     $requestValue = null;
     if (!empty($fields["{$fieldName}__delete"])) {
         //We never want to save this field, it doesn't exist in the DB
         $skip = "{$fieldName}__delete";
         //If user wants to delete the existing file
         if (!empty($request->input("{$groupName}.{$fieldName}__delete"))) {
             $adapter = new Local($basePath);
             $filesystem = new Filesystem($adapter);
             if ($filesystem->has($item->{$fieldName})) {
                 $filesystem->delete($item->{$fieldName});
             }
             $item->setAttribute($fieldName, null);
             return ['skip' => $skip];
         }
     }
     if ($request->hasFile($groupName . '.' . $fieldName)) {
         $fileName = uniqid() . '.' . $request->file($groupName . '.' . $fieldName)->getClientOriginalExtension();
         $request->file($groupName . '.' . $fieldName)->move($modelPath, $fileName);
         $requestValue = $modelFolder . $fileName;
     } elseif (!empty($request->file($groupName . '.' . $fieldName)) && !$request->file($groupName . '.' . $fieldName)->isValid()) {
         throw new \Exception($request->file($groupName . '.' . $fieldName)->getErrorMessage());
     }
     return ['requestValue' => $requestValue, 'skip' => $skip];
 }
Exemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 public function slash()
 {
     $app_path = str_replace(config('path.root'), '', config()->path->app);
     $arg_name = studly_case(str_slug($this->input->getArgument('name'), '_'));
     $stub = file_get_contents(__DIR__ . '/stubs/makeRoute.stub');
     $stub = stubify($stub, ['routeName' => $arg_name, 'prefixRouteName' => strtolower($arg_name)]);
     $file_name = $arg_name . 'Routes.php';
     $module = $this->input->getArgument('module');
     $has_dir = is_dir(config()->path->app . $module);
     if ($has_dir === false) {
         $this->error('Module not found `' . $module . '`');
         return;
     }
     $module = $this->input->getArgument('module');
     if ($this->app->has($module) === false) {
         $this->error('Module not found `' . $module . '`');
         return;
     }
     $routes = $module . '/routes/';
     if ($this->app->has($routes) === false) {
         $this->error('Routes folder not found from your module: `' . $module . '`');
         return;
     }
     $stub = stubify($stub, ['namespace' => path_to_namespace($app_path . $routes), 'controllerNamespace' => path_to_namespace($app_path . $module . '/controllers/')]);
     $this->info('Crafting Route...');
     if ($this->app->has($file_name)) {
         $this->error('   Route already exists!');
         return;
     }
     $this->app->put($routes . $file_name, $stub);
     $this->info('   ' . $file_name . ' created!');
     $this->callDumpAutoload();
 }
Exemplo n.º 19
0
 /**
  * @return Filesystem
  */
 public function getFilesystem()
 {
     if ($this->filesystem == null) {
         $this->filesystem = new Filesystem(new Local($this->path));
         $this->filesystem->addPlugin(new ListFiles());
     }
     return $this->filesystem;
 }
Exemplo n.º 20
0
 /**
  * {@inheritdoc}
  */
 public function write(Configuration $configuration)
 {
     $ini = $this->getRenderer()->render($configuration->toArray());
     if (false === ($result = $this->filesystem->put($this->file, $ini))) {
         throw new WriterException(sprintf('Cannot write configuration into file %s', $this->file));
     }
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function getArchive(JobExecution $jobExecution, $key)
 {
     $archives = $this->getArchives($jobExecution);
     if (!isset($archives[$key])) {
         throw new \InvalidArgumentException(sprintf('Key "%s" does not exist', $key));
     }
     return $this->filesystem->readStream($archives[$key]);
 }
Exemplo n.º 22
0
 public function writeStream($path, $resource)
 {
     try {
         return $this->filesystem->writeStream($path, $resource);
     } catch (FileExistsException $exception) {
         return $this->filesystem->updateStream($path, $resource);
     }
 }
Exemplo n.º 23
0
 function it_should_successfully_update_stream($path, Filesystem $filesystem)
 {
     $filesystem->writeStream($path, 'resource2')->willThrow('League\\Flysystem\\FileExistsException');
     $filesystem->updateStream($path, 'resource2')->willReturn(true);
     $this->writeStream($path, 'resource2');
     $filesystem->writeStream($path, 'resource2')->shouldBeCalled();
     $filesystem->updateStream($path, 'resource2')->shouldBeCalled();
 }
Exemplo n.º 24
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));
 }
Exemplo n.º 25
0
 /**
  * Removes a value from the cache.
  *
  * @param string $key A unique key
  *
  * @return bool True on success, false on failure.
  */
 public function remove($key)
 {
     try {
         return $this->filesystem->delete($key);
     } catch (FileNotFoundException $exception) {
         return false;
     }
 }
Exemplo n.º 26
0
 /**
  * Populates the "data" key with the file's JSON data
  *
  * @param array $file
  */
 private function addData(array &$file)
 {
     $data = json_decode($this->fs->read($file['path']), true);
     if ($data === null) {
         throw new \DomainException(sprintf('%s is not a valid JSON file.', $file['path']));
     }
     $file['data'] = $data;
 }
Exemplo n.º 27
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);
 }
 private function getFile($path)
 {
     try {
         return $this->filesystem->read($path);
     } catch (FileNotFoundException $e) {
         return null;
     }
 }
Exemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function remove(File $file) : bool
 {
     $key = $file->getKey();
     if ($this->filesystem->has($key)) {
         return $this->filesystem->delete($key);
     }
     return true;
 }
Exemplo n.º 30
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);
 }