public function listContents($directory = null) { $contents = $this->flysystem->listContents($directory); $collection = collect(); foreach ($contents as $object) { $collection->push($this->getType($object['type'], $object)); } return $collection; }
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(); }
/** * Flush will flush all cached data. */ public function flush() { $contents = $this->filesystem->listContents(); foreach ($contents as $content) { $this->filesystem->delete($content['basename']); } }
public function getResourcesList() { $resourcesToBackup = array(); $filesystemContents = $this->filesystem->listContents('', true); foreach ($filesystemContents as $content) { $resourcesToBackup[] = new RemoteResource($content['path'], $content['type']); } return $resourcesToBackup; }
public function posts() : Collection { return collect($this->filesystem->listContents('posts'))->filter(function (array $item) { return $item['type'] === 'dir'; })->flatMap(function (array $item) { return $this->filesystem->listContents($item['path']); })->map(function (array $item) { $contents = $this->getFile($item['path']); return $contents ? Article::create($this->frontMatterParser->parse($contents), url("{$item['dirname']}/{$item['filename']}")) : null; })->filter(function ($item) { return $item !== null; })->sort(function (Article $articleA, Article $articleB) { return $articleA->date->getTimeStamp() < $articleB->date->getTimeStamp(); }); }
public function testListContents() { $list = $this->filesystem->listContents(''); $this->assertArraySubset([['type' => 'file', 'path' => '2.txt'], ['type' => 'file', 'path' => '3.txt'], ['type' => 'dir', 'path' => 'test']], $list); $list = $this->filesystem->listContents('', true); $this->assertArraySubset([['type' => 'file', 'path' => '2.txt'], ['type' => 'file', 'path' => '3.txt'], ['type' => 'dir', 'path' => 'test'], ['type' => 'file', 'path' => 'test/1.txt']], $list); }
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); }
public function testListContents() { $rawListing = [['path' => 'other_root/file.txt'], ['path' => 'valid/to_deep/file.txt'], ['path' => 'valid/file.txt']]; $expected = [Util::pathinfo('valid/file.txt')]; $this->prophecy->listContents('valid', false)->willReturn($rawListing); $output = $this->filesystem->listContents('valid', false); $this->assertEquals($expected, $output); }
/** * @inheritdoc */ protected function _scandir($path) { $paths = array(); foreach ($this->fs->listContents($path, false) as $object) { $paths[] = $object['path']; } return $paths; }
public function file() { $adapter = new Local('app'); $filesystem = new Filesystem($adapter); $contents = $filesystem->listContents(); echo '<pre>'; print_r($contents); echo '</pre>'; }
/** * @return Collection */ private function getItemsToDelete() { return collect($this->filesystem->listContents("/Api"))->filter(function ($content) { if ($content['filename'] === "Endpoint") { return false; } return true; }); }
/** * Deploy files to the remote filesystem. * * @return void */ public function deployToRemote() { $local_path = $this->relativeDumpPath(); $files = $this->localAdapter->listContents($local_path); foreach ($files as $file) { $contents = $this->localAdapter->readStream($local_path . $file['basename']); $file_size = $this->localAdapter->getSize($local_path . $file['basename']); $this->out($this->parseString('Uploading %s (%s)', [$file['basename'], $this->formatBytes($file_size)], 'light_green')); $this->remoteAdapter->writeStream($local_path . $file['basename'], $contents); } }
/** * @param string $path * @return array */ public function foldersNames($path) { $files = $this->filesystem->listContents($path); $names = []; foreach ($files as $file) { if ($file['type'] === 'dir') { $names[] = $file['filename']; } } return $names; }
/** * @param string $providerPrefix * * @return bool */ public function invalidate($providerPrefix) { $pattern = $this->prefix . strtolower($providerPrefix) . '_'; $files = $this->filesystem->listContents(); foreach ($files as $file) { if (stripos($file['filename'], $pattern) === 0) { $this->filesystem->delete($file['filename']); } } return true; }
/** * {@inheritdoc} */ public function opendir($path) { try { $content = $this->flysystem->listContents($this->buildPath($path)); } catch (FileNotFoundException $e) { return false; } $names = array_map(function ($object) { return $object['basename']; }, $content); return IteratorDirectory::wrap($names); }
/** * Clean the cache dir. * * @throws \DomainException * @return void */ public static function cleanCache() { $filesystem = new Filesystem(new Local(self::$cacheDir)); foreach ($filesystem->listContents() as $path) { if ('dir' == $path['type']) { if (false == $filesystem->deleteDir($path['path'])) { throw new \DomainException('Can not clean the cache.'); } } } }
/** * Get an object from the filesystem based on its path. * * Dependening on the adapter in the underlying flysystem, this might treat * empty directories as if they would not exist (e.g. for ZipArchiveAdapter). * * @param string $path * @return FSObject|null */ public function get($path) { // TODO: This does not deal with ~ for home directory. assert(is_string($path)); // For ZipArchiveAdapter this is required to get the directories correctly, // as Filesystem::get will raise. if ($this->filesystem->listContents($path)) { return new Directory($this, $path); } try { $info = $this->filesystem->getMetadata($path); if ($info) { if ($info["type"] == "file") { return new File($this, $path); } return new Directory($this, $path); } } catch (\League\Flysystem\FileNotFoundException $e) { return null; } return null; }
/** * {@inheritdoc} */ public function flush() { $files = $this->filesystem->listContents(); foreach ($files as $file) { try { $this->filesystem->delete($file['path']); } catch (FileNotFoundException $e) { // don't care if we failed to unlink something, might have // been deleted by other process in the meantime... } } return true; }
/** * List the files and directories in the given directory path. * * @param string $path The subdirectory path within this directory * @param bool $recursive Find files and directories recursively * @param string[] $types Entry types to return ('file' and/or 'dir') * * @return Collection<File|Directory> * * @throws \InvalidArgumentException */ protected function getEntries($path = '', $recursive = true, $types = ['file', 'dir']) { $contents = $this->fs->listContents($this->getInternalPath($path), $recursive); if (!$contents) { $contents = []; } $contents = array_filter($contents, function ($metadata) use($types) { return in_array($metadata['type'], $types); }); return Collection\InMemory::fromArray(array_map(function ($metadata) { if ($metadata['type'] === 'file') { return new File($this, $metadata['path']); } return new self($this->fs, $this->local_path, $metadata['path']); }, $contents)); }
public function execute(InputInterface $input, OutputInterface $output) { $dir = $input->getOption("dir"); $dir = realpath(getcwd() . "/" . ($dir ?: "")); if (!is_dir($dir) || !is_writeable($dir)) { $output->writeln("<error>Given directory does not exists or is not writeable</error>"); return; } $fs = new Filesystem(new Adapter($dir)); $files = $fs->listContents("", true); $updates = []; $errors = 0; foreach ($files as $file) { if ($file['type'] === 'dir') { continue; } $content = $fs->read($file['path']); $content = preg_replace_callback(static::SEMVER_REGEX, function ($matches) use(&$updates, &$errors, $input) { list($prefix, $ver) = array_slice($matches, 1); try { $semver = new version($ver); } catch (\Exception $e) { $errors++; return $prefix . $ver; } if ($input->getOption("major")) { $semver->inc("major"); } elseif ($input->getOption("minor")) { $semver->inc("minor"); } elseif ($input->getOption("patch")) { $semver->inc("patch"); } else { $semver->inc("patch"); } if (!isset($updates[$ver])) { $updates[$ver] = ["count" => 0, "ver" => $semver->getVersion()]; } $updates[$ver]['count']++; return $prefix . $semver->getVersion(); }, $content); $fs->update($file['path'], $content); } foreach ($updates as $update => $count) { $output->writeln("<info>{$count['count']} files have been updated from {$update} to {$count['ver']}</info>"); } }
public function testDeleteResourceButLeaveOther() { $resourceDO = $this->getResourceDOMock(); $this->filesystem->put($resourceDO->getFilePath(), ''); $this->wrongFiles->create($resourceDO); $model = $this->filesystem->listContents('/', true); $model[30] = ['type' => 'dir', 'path' => 'testBase/testType/def/def/1', 'dirname' => 'testBase/testType/def/def', 'basename' => '1', 'filename' => '1']; $model[31] = ['type' => 'dir', 'path' => 'testBase/testType/def/def/1/c9f', 'dirname' => 'testBase/testType/def/def/1', 'basename' => 'c9f', 'filename' => 'c9f']; $model[32] = ['type' => 'file', 'visibility' => 'public', 'size' => 0, 'path' => 'testBase/testType/def/def/1/c9f/c9f7e81bafc626421e04b573022e6203.testType', 'dirname' => 'testBase/testType/def/def/1/c9f', 'basename' => 'c9f7e81bafc626421e04b573022e6203.testType', 'extension' => 'testType', 'filename' => 'c9f7e81bafc626421e04b573022e6203']; $command = $this->getCommand($resourceDO); $result = $command(); $this->assertEquals($resourceDO, $result); $this->assertFalse($this->filesystem->has($resourceDO->getFilePath())); $result = $this->filesystem->listContents('/', true); unset($result[32]['timestamp']); $this->assertEquals($model, $result); }
/** * Rename lessons, adding 0 padding to the number. */ public function renameLessonsWithRightPadding() { $list = $this->system->listContents(LESSONS_FOLDER); foreach ($list as $entry) { if ($entry['type'] != 'file') { continue; } $originalName = $entry['basename']; $oldNumber = substr($originalName, 0, strpos($originalName, '-')); if (strlen($oldNumber) == 4) { continue; } // already correct $newNumber = sprintf("%04d", $oldNumber); $nameWithoutNumber = substr($originalName, strpos($originalName, '-') + 1); $newName = $newNumber . '-' . $nameWithoutNumber; $this->system->rename(LESSONS_FOLDER . '/' . $originalName, LESSONS_FOLDER . '/' . $newName); } }
public function execute(InputInterface $input, OutputInterface $output) { $version = $input->getArgument("version"); try { $semver = new version($version); } catch (\Exception $e) { $output->writeln("<error>Given version is not valid. Please provide a semver version</error>"); return; } $version = $semver->getVersion(); $dir = $input->getOption("dir"); $dir = realpath(getcwd() . "/" . ($dir ?: "")); if (!is_dir($dir) || is_writeable($dir)) { $output->writeln("Given directory does not exists or is not writeable"); return; } $fs = new Filesystem(new Adapter($dir)); $files = $fs->listContents("", true); $updates = []; foreach ($files as $file) { if ($file['type'] === 'dir') { continue; } $content = $fs->read($file['path']); $content = preg_replace_callback(static::SEMVER_REGEX, function ($matches) use($version, &$updates) { list($prefix, $ver) = array_slice($matches, 1); if (!isset($updates[$ver])) { $updates[$ver] = 0; } $updates[$ver]++; return $prefix . $version; }, $content); $fs->update($file['path'], $content); } foreach ($updates as $update => $count) { $output->writeln("<info>{$count} files have been updated from {$update} to {$version}</info>"); } }
/** * @param Filesystem $source The source file system to archive * @param string $archiveFile The name of the archive/zip file. Extension is optional, allowing me to decide * * @return bool|string If successful, the actual file name (without a path) is return. False otherwise */ protected static function archiveTree(Filesystem $source, $archiveFile) { // Add file extension if missing $archiveFile = static::ensureFileSuffix('.zip', $archiveFile); // Create our zip container $_archive = new Filesystem(new ZipArchiveAdapter($archiveFile)); try { foreach ($source->listContents('', true) as $_file) { if ('dir' == $_file['type']) { $_archive->createDir($_file['path']); } elseif ('link' == $_file['type']) { $_archive->put($_file['path'], $_file['target']); } elseif ('file' == $_file['type']) { file_exists($_file['path']) && static::writeStream($_archive, $_file['path'], $_file['path']); } } } catch (\Exception $_ex) { \Log::error('Exception exporting instance storage: ' . $_ex->getMessage()); return false; } // Force-close the zip static::flushZipArchive($_archive); return basename($archiveFile); }
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)); }
public function isActive($identifier) { $exists = false; $adapter = new Local('/var/www/crm_container'); $filesystem = new Filesystem($adapter); $contents = $filesystem->listContents('/'); foreach ($contents as $directory) { if ($directory['basename'] == $identifier) { $exists = true; return $exists; } } return $exists; }
$auth_token = '{"access_token":"ya29.IQD9DFJHv7U1kBgAAAAJSdBBwvJq8lmEj8f9RBsXbK5uX82vXlvlQAbn_pL2Rg","token_type":"Bearer","expires_in":3600,"refresh_token":"1\\/_RAFGmxs0bQBSCCI3hJYnntuGiyXq28UGCdsW8E1cb4","created":1401030654}'; // This URL should be the landing page after authorising the site access to your Google Drive. // It should store your $auth_token or display it for manual entry. $redirect_url = 'http://localhost/flysystem/GoogleDriveSetup.php'; $client = new Google_Client(); $client->setAccessToken($auth_token); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_url); $token = $client->getAccessToken(); if (isset($auth_token)) { $refreshToken = json_decode($token); $refreshToken = $refreshToken->refresh_token; if ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshToken($refreshToken); } } else { if (isset($_GET['code'])) { $client->authenticate($_GET["code"]); echo "Your access token for Google Drive is:<br /><br />\n\n"; echo $client->getAccessToken(); echo "\n\n<br /><br />This is your \$auth_token value. Set it in the configuration file."; exit; } else { $authUrl = $client->createAuthUrl(); die("You must first authorise the plugin. Make sure your client ID and secret are set then <a href='{$authUrl}'>click here</a> to do so."); } } $filesystem = new Filesystem(new Adapter($client)); echo nl2br(print_r($filesystem->listContents("/"), true));
/** * Get all of the directories within a given directory. * * @param string|null $directory * @param bool $recursive * @return array */ public function directories($directory = null, $recursive = false) { $contents = parent::listContents($directory, $recursive); return $this->filterContentsByType($contents, 'dir'); }
/** * Returns an iterable {@see Generator} of all files / variants for the given $fileID in the given $filesystem * This includes the empty (no) variant. * * @param string $fileID ID of original file to compare with. * @param Filesystem $filesystem * @return Generator */ protected function findVariants($fileID, Filesystem $filesystem) { $dirname = ltrim(dirname($fileID), '.'); foreach ($filesystem->listContents($dirname) as $next) { if ($next['type'] !== 'file') { continue; } $nextID = $next['path']; // Compare given file to target, omitting variant if ($fileID === $this->removeVariant($nextID)) { (yield $nextID); } } }
/** * Display an error "page" if no options have been found for a given command. * * @param string $dir The base directory for the commands. * * @return $this * * @since 1.0 */ public function displayMissingOption($dir) { $command = strtolower(join('', array_slice(explode('\\', get_class($this)), -1))); $this->getApplication()->outputTitle(sprintf(g11n3t('Command: %s'), ucfirst($command))); $errorTitle1 = g11n3t(sprintf('Missing option for command: %s', $command)); $errorTitle2 = g11n3t('Please use one of the following :'); $maxLen = strlen($errorTitle1) > strlen($errorTitle2) ? strlen($errorTitle1) : strlen($errorTitle2); $filesystem = new Filesystem(new Local($dir)); $this->out('<error> ' . str_repeat(' ', $maxLen) . ' </error>'); $this->out('<error> ' . $errorTitle1 . str_repeat(' ', $maxLen - strlen($errorTitle1)) . ' </error>'); $this->out('<error> ' . $errorTitle2 . str_repeat(' ', $maxLen - strlen($errorTitle2)) . ' </error>'); $this->out('<error> ' . str_repeat(' ', $maxLen) . ' </error>'); $files = $filesystem->listContents(); sort($files); foreach ($files as $file) { $cmd = strtolower($file['filename']); if ('file' != $file['type'] || $command == $cmd) { // Exclude the base class continue; } $this->out('<error> ' . $command . ' ' . $cmd . str_repeat(' ', $maxLen - strlen($cmd) - strlen($command) + 1) . '</error>'); } $this->out('<error> ' . str_repeat(' ', $maxLen) . ' </error>'); }