/** * Remove file or a directory * * @param $path * @return void */ public function remove($path) { if (!$this->filesystem->has($path)) { return; } $meta = $this->filesystem->getMetadata($path); if ($meta['type'] === 'file') { $this->filesystem->delete($path); } else { $this->filesystem->deleteDir($path); } }
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']]); }
/** * {@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(); }
/** * {@inheritdoc} */ public function remove(File $file) : bool { $key = $file->getKey(); if ($this->filesystem->has($key)) { return $this->filesystem->delete($key); } return true; }
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); }
/** * Check if key exists. * * @param string $key * * @return bool */ public function exists($key) { if (!is_string($key)) { return false; } $file = $this->get_file_name($key); return $this->filesystem->has($file); }
/** * @param string $providerPrefix * @param string $uri * @param string $query * * @return bool */ public function delete($providerPrefix, $uri, $query) { $hash = $this->getHash($providerPrefix, $uri, $query); if ($this->filesystem->has($hash)) { return $this->filesystem->delete($hash); } return false; }
/** * {@inheritdoc} */ public function parse(Configuration $configuration = null) { if (!$this->filesystem->has($this->file)) { throw new ParsingFailed(sprintf('File "%s" not found', $this->file)); } $fileContents = $this->filesystem->read($this->file); $parser = new Text($fileContents); return $parser->parse($configuration); }
public function testAddsNamespaceToSubClass() { $generator = $this->getGenerator(); $generator->generateForEndpoint("Users/Followers"); static::$content = $generator->getGeneratedTemplate(); $check = $this->filesystem->has('Users/Followers.php'); $this->assertTrue($check); $this->assertContains("Wubs\\Trakt\\Api\\Users", static::$content); }
/** * @param File $file * @param Version $version * @param VersionProvider $versionProvider * @param Linker $linker * @return bool */ public function unpublish(File $file, Version $version, VersionProvider $versionProvider, Linker $linker) { $path = $linker->getLink($file, $version, $versionProvider->getExtension($file, $version)); if (!$this->filesystem->has($path)) { return false; } $this->filesystem->delete($path); return true; }
/** * @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; }
/** * @test */ public function publishesAndUnpublishes() { $this->assertFalse($this->filesystem->has($this->path)); $this->assertTrue($this->adapter->publish($this->file, Version::get('xooxer'), $this->vp, $this->linker)); $this->assertTrue($this->filesystem->has($this->path)); $this->assertFalse($this->adapter->publish($this->file, Version::get('xooxer'), $this->vp, $this->linker)); $this->assertTrue($this->adapter->unpublish($this->file, Version::get('xooxer'), $this->vp, $this->linker)); $this->assertFalse($this->filesystem->has($this->path)); $this->assertFalse($this->adapter->unpublish($this->file, Version::get('xooxer'), $this->vp, $this->linker)); }
/** * @inheritdoc */ public function fetch($key) { if ($this->filesystem->has($key)) { // The file exist, read it! $data = @unserialize($this->filesystem->read($key)); if ($data instanceof CacheEntry) { return $data; } } return; }
/** * Checks if the underlying flysystem contains a file of the given name. * * @param string $name * * @return \League\Flysystem\File|\League\Flysystem\Handler * @throws Twig_Error_Loader */ protected function getFileOrFail($name) { if (!$this->filesystem->has($this->resolveTemplateName($name))) { throw new Twig_Error_Loader('Template could not be found on the given filesystem'); } $fileObject = $this->filesystem->get($this->resolveTemplateName($name)); if ($fileObject->isDir()) { throw new Twig_Error_Loader('Cannot use directory as template'); } return $fileObject; }
/** * Returns the historical price data as a csv string for $ticker * @param string $ticker * @param bool $fromCache * @param bool $saveToCache * @param bool $return * @return TickerCollection */ public function getData($ticker, $fromCache = true, $saveToCache = true, $return = true) { if ($fromCache && $this->fileSystem->has($ticker)) { return $this->present($ticker, $this->fileSystem->read($ticker)); } $data = (string) $this->guzzle->request('GET', '', ['query' => ['s' => $ticker, 'ignore' => '.csv']])->getBody(); if ($saveToCache) { $this->fileSystem->put($ticker, $data); } if ($return) { return $this->present($ticker, $data); } }
public function testGeneratesClassFile() { $outMock = Mockery::mock(OutputInterface::class); $outMock->shouldReceive("writeln"); $outMock->shouldReceive("write")->andReturn(true); $inMock = Mockery::mock(InputInterface::class); $dialog = Mockery::mock(QuestionHelper::class); $dialog->shouldReceive("ask")->andReturn(true); $generator = new EndpointGenerator($inMock, $outMock, $dialog); $generator->generateForEndpoint("Comments"); $this->assertTrue($this->filesystem->has("Comments.php")); self::$content = $generator->getGeneratedTemplate(); }
/** * {@inheritdoc} */ public function load(Configuration $configuration = null) { if (!$this->filesystem->has($this->file)) { throw new LoaderException(sprintf('File "%s" not found', $this->file)); } if (!($fileContents = $this->filesystem->read($this->file))) { throw new LoaderException(sprintf('Reading file "%s" failed', $this->file)); } try { $ini = $this->getParser()->parse($fileContents); } catch (ParserException $e) { throw new LoaderException('Cannot parse INI', 0, $e); } return $this->parseSections($ini, $configuration); }
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]; }
/** * 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; }
/** * Cleanup output files after each test */ public function tearDown() { $cleanup = ['sprite.jpg', 'sprite.vtt', 'blubber.jpg', 'blubber.vtt']; foreach ($cleanup as $file) { $this->outputFS->has($file) && $this->outputFS->delete($file); } }
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')); }
public function testDestroyResourceAllVariantsAndVersions() { $resourceDO = $this->getResourceDOMock(); $this->filesystem->put($resourceDO->getFilePath(), ''); $resourceDO_v2 = clone $resourceDO; $resourceDO_v2->setVersion(2); $this->filesystem->put($resourceDO_v2->getFilePath(), ''); $resourceDO_var1 = clone $resourceDO; $resourceDO_var1->setVariant('1'); $this->filesystem->put($resourceDO_var1->getFilePath(), ''); // variant version must be deleted too $resourceDO_var1_v1 = clone $resourceDO_var1; $resourceDO_var1_v1->setVersion(1); $this->filesystem->put($resourceDO_var1_v1->getFilePath(), ''); $resourceDO_var2 = clone $resourceDO; $resourceDO_var2->setVariant('2'); $this->filesystem->put($resourceDO_var2->getFilePath(), ''); $resourceDO_var2_v1 = clone $resourceDO_var2; $resourceDO_var2_v1->setVersion(2); $this->filesystem->put($resourceDO_var2_v1->getFilePath(), ''); $command = $this->getCommand($resourceDO); $result = $command(); $this->assertEquals($resourceDO, $result); $this->assertFalse($this->filesystem->has($resourceDO_var1->getFilePath())); $this->assertFalse($this->filesystem->has($resourceDO_var1_v1->getFilePath())); $this->assertFalse($this->filesystem->has($resourceDO_v2->getFilePath())); $this->assertFalse($this->filesystem->has($resourceDO_var2->getFilePath())); $this->assertFalse($this->filesystem->has($resourceDO_var2_v1->getFilePath())); $this->assertFalse($this->filesystem->has($resourceDO->getFilePath())); }
protected function checkProjectName() { if ($this->fs->has(DIRECTORY_SEPARATOR . $this->projectName)) { throw new \RuntimeException(sprintf("There is already a '%s' project created.\n" . 'Change your project name to create a new project please.', $this->projectName)); } return $this; }
/** * 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; } }
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); }
/** * 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 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); }
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'); } }
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; }
/** * Process give source file with given options * * @param array $options * @param $sourceFile * @return string */ public function process($options, $sourceFile) { //check restricted_domains is enabled if ($this->params['restricted_domains'] && is_array($this->params['whitelist_domains']) && !in_array(parse_url($sourceFile, PHP_URL_HOST), $this->params['whitelist_domains'])) { throw new \Exception('Restricted domains enabled, the domain your fetching from is not allowed: ' . parse_url($sourceFile, PHP_URL_HOST)); } $options = $this->parseOptions($options); $newFileName = md5(implode('.', $options) . $sourceFile); if ($this->filesystem->has($newFileName) && $options['refresh']) { $this->filesystem->delete($newFileName); } if (!$this->filesystem->has($newFileName)) { $this->saveNewFile($sourceFile, $newFileName, $options); } return $this->filesystem->read($newFileName); }