/** * @ORM\PreFlush() */ public function preUpload() { if ($this->file) { if ($this->file instanceof FileUpload) { $basename = $this->file->getSanitizedName(); $basename = $this->suggestName($this->getFilePath(), $basename); $this->setName($basename); } else { $basename = trim(Strings::webalize($this->file->getBasename(), '.', FALSE), '.-'); $basename = $this->suggestName(dirname($this->file->getPathname()), $basename); $this->setName($basename); } if ($this->_oldPath && $this->_oldPath !== $this->path) { @unlink($this->getFilePathBy($this->_oldProtected, $this->_oldPath)); } if ($this->file instanceof FileUpload) { $this->file->move($this->getFilePath()); } else { copy($this->file->getPathname(), $this->getFilePath()); } return $this->file = NULL; } if (($this->_oldPath || $this->_oldProtected !== NULL) && ($this->_oldPath != $this->path || $this->_oldProtected != $this->protected)) { $oldFilePath = $this->getFilePathBy($this->_oldProtected !== NULL ? $this->_oldProtected : $this->protected, $this->_oldPath ?: $this->path); if (file_exists($oldFilePath)) { rename($oldFilePath, $this->getFilePath()); } } }
public function __destruct() { if ($this->unlinkOnDestroy) { @unlink($this->file->getPathname()); @rmdir(dirname($this->file->getPathname())); } }
/** * {@inheritdoc} */ public function loadManifest(\SplFileInfo $manifestFile, $build, $development = false) { $manifest = json_decode(file_get_contents($manifestFile->getPathname()), true); $pathMapper = function ($path) use($build, $development) { return $this->pathMapper->mapPath($path, $build, $development); }; $mapArray = function (array $u) use($pathMapper) { $u['path'] = $pathMapper($u['path']); return $u; }; $manifest['js'] = array_map($mapArray, $manifest['js']); $manifest['css'] = array_map($mapArray, $manifest['css']); if (isset($manifest['resources'])) { $manifest['resources'] = array_map($pathMapper, $manifest['resources']); } if ($development && isset($manifest['paths'])) { $manifest['paths'] = array_map($pathMapper, $manifest['paths']); } if ($development && isset($manifest['loadOrder'])) { $manifest['loadOrder'] = array_map($mapArray, $manifest['loadOrder']); } foreach (clone $this->manifestMutators as $manifestMutator) { $manifest = $manifestMutator($manifest, $build, $development); } return new Manifest($manifestFile->getPathname(), $manifest); }
protected function execute(InputInterface $input, OutputInterface $output) { $configHelper = $this->getHelper('configuration'); /* @var $configHelper GlobalConfigurationHelper */ $questionHelper = $this->getHelper('question'); /* @var $questionHelper QuestionHelper */ $sshConfig = new \SplFileInfo($configHelper->getConfiguration()->getSshDirectory() . '/config'); if (!$sshConfig->isFile()) { throw new NotAFileException($sshConfig); } if (!$sshConfig->isReadable()) { throw new UnreadableFileException($sshConfig); } if (!$sshConfig->isWritable()) { throw new UnwritableFileException($sshConfig); } $sshConfigLines = file($sshConfig->getPathname()); $repoName = $input->getArgument('repository'); $repositoryConfig = $configHelper->getConfiguration()->getRepositoryConfiguration($repoName); if (!$questionHelper->ask($input, $output, new ConfirmationQuestion(sprintf('Are you sure you want to remove the ssh key for "%s"? This action is irreversible.', $repoName)))) { return 1; } $sshKeyFile = $repositoryConfig->getIdentityFile(); $this->unlinkFile($output, $sshKeyFile); $this->unlinkFile($output, $sshKeyFile . '.pub'); if (Util::removeSshAliasLines($sshConfigLines, $repositoryConfig)) { $output->writeln(sprintf('Removed section <info>Host %s</info> from <info>%s</info>', $repositoryConfig->getSshAlias(), $sshConfig->getPathname()), OutputInterface::VERBOSITY_VERBOSE); } $output->writeln(sprintf('Removed repository <info>%s</info>', $repoName)); $configHelper->getConfiguration()->removeRepositoryConfiguration($repoName); FsUtil::file_put_contents($sshConfig->getPathname(), implode('', $sshConfigLines)); $configHelper->getConfiguration()->write(); return 0; }
public function testInitializeFromEmptySchema() { $pdo = $this->aNewInitializedSchema(); $sqlDirectory = new \SplFileInfo(__DIR__ . "/../testsets/nummericsorting"); $files = call_user_func(new MigrateDryRun($pdo, $sqlDirectory)); $this->assertEquals([new SqlFile(new \SplFileInfo($sqlDirectory->getPathname() . "/v3_test.sql")), new SqlFile(new \SplFileInfo($sqlDirectory->getPathname() . "/v10_test.sql"))], $files); }
protected function generateSourceCode(ParsedType $type, SourceBuffer $buffer, \SplFileInfo $file) { $extends = array_map(function ($t) { return '\\' . ltrim($t, '\\'); }, $type->getExtends()); $extends = empty($extends) ? '' : implode(', ', $extends); $implements = ['\\' . MergedSourceInterface::class]; // Double inclusion safeguard: if ($type->isClass()) { $safe1 = sprintf(' if(!class_exists(%s, false)) { ', var_export($type->getName(), true)); $safe2 = ' } '; } elseif ($type->isInterface()) { $safe1 = sprintf(' if(!interface_exists(%s, false)) { ', var_export($type->getName(), true)); $safe2 = ' } '; } else { $safe1 = sprintf(' if(!trait_exists(%s, false)) { ', var_export($type->getName(), true)); $safe2 = ' } '; } $generator = new SourceGenerator($buffer); $generator->populateTypeMarker($type, ParsedType::MARKER_INTRODUCED_INTERFACES, implode(', ', $implements)); $generator->populateTypeMarker($type, ParsedType::MARKER_INTRODUCED_NAME, $type->getLocalName()); $generator->populateTypeMarker($type, ParsedType::MARKER_INTRODUCED_SUPERCLASS, $extends); $generator->populateTypeMarker($type, ParsedType::MARKER_INTRODUCED_PREPENDED_CODE, $safe1); $generator->populateTypeMarker($type, ParsedType::MARKER_INTRODUCED_EXTERNAL_CODE, $safe2); $code = trim($generator->generateCode($file->getPathname(), dirname($file->getPathname()))); $code = preg_replace("'^<\\?(?:php)?'i", '', $code) . "\n"; return $code; }
/** * Creates a new image on the path which is set * * @return SplFileInfo */ public function createImage() { if (!$this->imageoutput($this->outputPath->getPathname(), strtolower($this->originalPath->getExtension()))) { throw new ImageResourceException("Could not create image on " . $this->outputPath); } return new \SplFileInfo($this->outputPath); }
public function register($fileinfo) { //parse module if (!$fileinfo instanceof \SplFileInfo) { $fileinfo = new \SplFileInfo($fileinfo); } echo sprintf("scan module %s in folder %s\n", $fileinfo->getFilename(), $fileinfo->getPathname()); $info_filename = $fileinfo->getPathname() . DIRECTORY_SEPARATOR . 'module.info'; $module_info = parse_ini_file($info_filename); if (!isset($module_info['c_name'])) { $module_info['c_name'] = $fileinfo->getFilename(); } $dbal = DBAL::insert(\ORC\APP\Module::TABLENAME_MODULE); $dbal->set('name', $module_info['name']); $dbal->set('c_name', $module_info['c_name']); $dbal->set('description', empty($module_info['description']) ? '' : $module_info['description']); $dbal->set('dependence', empty($module_info['dependence']) ? '' : implode(',', $module_info['dependence'])); //$dbal->set('permissions', empty($module_info['permissions']) ? '' : implode(',', $module_info['permissions'])); $dbal->setDuplicate(array('name', 'description', 'dependence')); $dbal->execute(); echo "\tdb done.\n"; if (!empty($module_info['permissions'])) { $dbal = DBAL::insert(\ORC\APP\Module::TABLENAME_PERMS); foreach ($module_info['permissions'] as $perm) { $dbal->set('perm', $perm); $dbal->setDuplicate('perm'); $dbal->execute(); } echo "\tpermission done.\n"; } //check actions $folder = $fileinfo->getPathname() . DIRECTORY_SEPARATOR . 'actions'; $this->scanActions($module_info['c_name'], $folder); }
/** * Scans an individual view file, adding it's version number (if found) to the * $this->views array. * * @param SplFileInfo $file */ protected function scan_view(SplFileInfo $file) { if (!$file->isFile() || !$file->isReadable()) { return; } $version = $this->get_template_version($file->getPathname()); $this->originals[$this->short_name($file->getPathname())] = $version; }
/** * upload * * @param \JInput $input */ public static function upload(\JInput $input) { try { $editorPlugin = \JPluginHelper::getPlugin('editors', 'akmarkdown'); if (!$editorPlugin) { throw new \Exception('Editor Akmarkdown not exists'); } $params = new Registry($editorPlugin->params); $files = $input->files; $field = $input->get('field', 'file'); $type = $input->get('type', 'post'); $allows = $params->get('Upload_AllowExtension', ''); $allows = array_map('strtolower', array_map('trim', explode(',', $allows))); $file = $files->getVar($field); $src = $file['tmp_name']; $name = $file['name']; $tmp = new \SplFileInfo(JPATH_ROOT . '/tmp/ak-upload/' . $name); if (empty($file['tmp_name'])) { throw new \Exception('File not upload'); } $ext = pathinfo($name, PATHINFO_EXTENSION); if (!in_array($ext, $allows)) { throw new \Exception('File extension now allowed.'); } // Move file to tmp if (!is_dir($tmp->getPath())) { \JFolder::create($tmp->getPath()); } if (is_file($tmp->getPathname())) { \JFile::delete($tmp->getPathname()); } \JFile::upload($src, $tmp->getPathname()); $src = $tmp; $dest = static::getDest($name, $params->get('Upload_S3_Subfolder', 'ak-upload')); $s3 = new \S3($params->get('Upload_S3_Key'), $params->get('Upload_S3_SecretKey')); $bucket = $params->get('Upload_S3_Bucket'); $result = $s3::putObject(\S3::inputFile($src->getPathname(), false), $bucket, $dest, \S3::ACL_PUBLIC_READ); if (is_file($tmp->getPathname())) { \JFile::delete($tmp->getPathname()); } if (!$result) { throw new \Exception('Upload fail.'); } } catch (\Exception $e) { $response = new Response(); $response->setBody(json_encode(['error' => $e->getMessage()])); $response->setMimeType('text/json'); $response->respond(); exit; } $return = new \JRegistry(); $return['filename'] = 'https://' . $bucket . '.s3.amazonaws.com/' . $dest; $return['file'] = 'https://' . $bucket . '.s3.amazonaws.com/' . $dest; $response = new Response(); $response->setBody((string) $return); $response->setMimeType('text/json'); $response->respond(); }
/** * @param $path * * @return \SplFileInfo */ protected function getFilePath($path) { $contentdir = $this->contentDir->getPathname() . DIRECTORY_SEPARATOR; $file = $contentdir . $path; if (!is_file($file)) { throw new FileNotFoundException($path); } return new \SplFileInfo($file); }
/** @return SqlFile[] */ public function listSqlFiles() { $foundFiles = glob($this->scanDir->getPathname() . "/*.[sS][qQ][lL]"); natsort($foundFiles); $foundFiles = array_values($foundFiles); return array_map(function ($file) { return new SqlFile(new \SplFileInfo($file)); }, $foundFiles); }
/** * @param \SplFileInfo $file * * @throws FileRemovalException */ protected function deleteRawFile(\SplFileInfo $file) { $fs = new Filesystem(); try { $fs->remove($file->getPathname()); } catch (IOException $e) { throw new FileRemovalException(sprintf('Unable to delete the file "%s".', $file->getPathname()), $e->getCode(), $e); } }
/** * createThumb * * @param string $src * * @return bool */ public static function createThumb($src, $width = 400, $height = 400) { $dest = new \SplFileInfo(WINDWALKER_CACHE . '/image/temp/' . md5($src)); Folder::create($dest->getPath()); $image = new Image(); $image->loadFile($src); $image->cropResize($width, $height, false); $image->toFile($dest->getPathname() . '.jpg'); return $dest->getPathname() . '.jpg'; }
/** * @param \SplFileInfo $package * @return array * @throws \movi\FileNotFoundException */ private function getData(\SplFileInfo $package) { $file = $package->getPathname() . '/' . self::PACKAGE_FILE; if (!file_exists($file) || !is_readable($file)) { throw new FileNotFoundException("JSON file for package '" . $package->getFilename() . "' was not found or is not readable."); } $data = Json::decode(file_get_contents($file), Json::FORCE_ARRAY); $data['dir'] = $package->getPathname(); return Arrays::mergeTree($data, $this->defaults); }
/** * @param mixed $item * * @return array<\SplFileInfo, string> */ public function convert($item) { if ($item instanceof \SplFileInfo === false) { $item = new \SplFileInfo($item); } if ($item->isReadable() === false) { throw new \InvalidArgumentException(sprintf('The given file "%s" is not readable.', $item->getPathname())); } return ['file' => $item, 'content' => file_get_contents($item->getPathname())]; }
/** * * @param \SplFileInfo $value1 * @param \SplFileInfo $value2 */ protected function compare($value1, $value2) { switch (true) { case $value1->getPathname() > $value2->getPathname(): return 1; case $value1->getPathname() < $value2->getPathname(): return -1; default: return 0; } }
protected function calculateTargetPath(\SplFileInfo $file) { $pattern = $this->sourceBasePath->getPathname(); $pattern = '|^' . str_replace('|', '\\|', $pattern) . '|'; $fromPath = new \SplFileInfo(preg_replace($pattern, '', $file->getPathname())); if (!isset($this->filemap[$fromPath->getPathname()])) { throw new \InvalidArgumentException("no mapping found for \"{$file}\""); } $result = new \SplFileInfo($this->targetBasePath->getPathname() . $this->filemap[$fromPath->getPathname()]); return $result; }
private function saveImage(\SplFileInfo $original, \SplFileInfo $destination, $image) { switch ($original->getExtension()) { case 'jpg': case 'jpeg': return imagejpeg($image, $destination->getPathname()); case 'png': return imagepng($image, $destination->getPathname()); case 'gif': return imagegif($image, $destination->getPathname()); } }
/** * Loads the contents of the given file and replaces %-delimited placeholders * with the given values. * * @param \SplFileInfo $source * @param array<string, mixed> $params * @return string * * @throws \RuntimeException When the file could not be accessed. */ protected function loadSource(\SplFileInfo $source, array $params = []) { $cfg = @file_get_contents($source->getPathname()); if ($cfg === false) { throw new \RuntimeException(sprintf('Configuration source not found: "%s"', $source->getPathname())); } $replacements = []; foreach ($params as $k => $v) { $replacements['%' . $k . '%'] = trim($v); } return trim(strtr($cfg, $replacements)); }
/** * Writes the class to a file. */ public function write() { try { $dir = $this->path->isDir() ? $this->path->getPathname() : $this->path->getPath(); $path = $dir . '/' . $this->baseClass->getClassName() . $this->baseClass->getExtension(); if (!file_exists($dir)) { $this->fileSystem->mkdir($dir, 0777, true); } //if (!file_exists($path)) { file_put_contents($path, $this->baseClass->generate()); //} } catch (IOExceptionInterface $e) { } }
protected function loadCachedFile() { if (!$this->cacheFile->isReadable()) { return null; } if ($this->cacheFile->getMTime() < $this->dataFile->getMTime()) { return null; } $jsonString = file_get_contents($this->cacheFile->getPathname()); if (false === $jsonString) { throw new InvalidArgumentException("Can not read file content from '{$this->cacheFile->getPathname()}'!"); } return CiteCollection::loadFromJson($jsonString); }
public function __construct(\SplFileInfo $file) { if (!$file->isFile()) { throw new \InvalidArgumentException("File " . $file->getPathname() . " ist not a normal file"); } if (!is_readable($file->getPathname())) { throw new MigrationException("File " . $file->getPathname() . " can't be read (no permissions)"); } $this->file = $file; $this->contents = file_get_contents($file->getPathname()); if ($this->contents === false) { $error = error_get_last(); throw new MigrationException("File " . $file->getPathname() . " can't be read (" . $error["message"] . ")"); } }
/** * * @param SplFileInfo $file * @param stdClass $prefix * @param string $prefixedPath * @return Magelog_Mql_Model_Model */ public function getModelInfo(SplFileInfo $file, $prefixInfo, $prefixedPath) { $fileName = $file->getFilename(); if (!fnmatch('*.php', $fileName)) { return false; } $pathName = $file->getPathname(); // skip resource models that are already processed by the preceding resource namespace if (isset($this->_filesProcessed[$pathName])) { return false; } $this->_filesProcessed[$pathName] = 1; $prefix = $prefixInfo->prefix; $basename = substr(substr(trim($file->getPathname()), 1 + strlen($prefixedPath)), 0, -4); $shortName = implode('_', array_map('lcfirst', explode('/', $basename))); $className = Mage::getConfig()->getModelClassName($prefix . '/' . $shortName); $model = Mage::getModel('mql/model')->setShortname($shortName)->setClass($className)->setPrefix($prefixInfo->prefix)->setIsResource($prefixInfo->isResource)->setResourcePrefix(isset($prefixInfo->resourcePrefix) ? $prefixInfo->resourcePrefix : '')->setFilename(str_replace(Mage::getBaseDir() . '/', '', $pathName))->setError('')->setIsBlacklisted(isset(self::$blacklist[$className])); if (stripos(file_get_contents($pathName), $className) === false) { echo $className . PHP_EOL; $model->setError('File does not contain class')->setIsBlacklisted(true); } if (!$model->getIsBlacklisted()) { $model->setIsUsable(true); try { $parentClasses = class_parents($className, true); $reflectionClass = new ReflectionClass($className); $model->setIsException(in_array('Exception', $parentClasses)); $model->setIsDbCollection(in_array('Varien_Data_Collection_Db', $parentClasses)); $model->setIsCollection(in_array('Varien_Data_Collection', $parentClasses)); $model->setIsInstantiable($reflectionClass->isInstantiable() && !$reflectionClass->isAbstract() && substr($shortName, strlen($shortName) - strlen('abstract')) != 'abstract'); #echo $model->getPrefix().'/'.$model->getShortname().' => '.$pathName.PHP_EOL; $model->setIsGetModelInstantiable(false); if ($model->getPrefix() != 'varien' && !$model->getIsException() && $model->getIsInstantiable()) { try { $testModel = Mage::getModel($model->getPrefix() . '/' . $model->getShortname()); unset($testModel); $model->setIsGetModelInstantiable(true); } catch (Exception $e) { #echo $e->getMessage().PHP_EOL; } } } catch (Magelog_Mql_Model_Model_Exception $e) { $model->setError($e->getMessage()); $model->setIsUsable(false); } } return $model; }
/** * @param \SplFileInfo $basePath * @param Property $property * @return self */ public static function fromProperty(\SplFileInfo $basePath, Property $property) { $filePath = sprintf(self::FILE_PATH_FORMAT, $basePath->getPathname(), $property); $fileInfo = new \SplFileInfo($filePath); $file = new PHPFile($fileInfo); return new self($file, $property); }
protected function createTransferAction(\SplFileInfo $file) { // Open the file for reading $filename = $file->getRealPath() ?: $file->getPathName(); if (!($resource = fopen($filename, 'r'))) { // @codeCoverageIgnoreStart throw new RuntimeException('Could not open ' . $file->getPathname() . ' for reading'); // @codeCoverageIgnoreEnd } $key = $this->options['source_converter']->convert($filename); $body = EntityBody::factory($resource); // Determine how the ACL should be applied if ($acl = $this->options['acl']) { $aclType = is_string($this->options['acl']) ? 'ACL' : 'ACP'; } else { $acl = 'private'; $aclType = 'ACL'; } // Use a multi-part upload if the file is larger than the cutoff size and is a regular file if ($body->getWrapper() == 'plainfile' && $file->getSize() >= $this->options['multipart_upload_size']) { $builder = UploadBuilder::newInstance()->setBucket($this->options['bucket'])->setKey($key)->setMinPartSize($this->options['multipart_upload_size'])->setOption($aclType, $acl)->setClient($this->options['client'])->setSource($body)->setConcurrency($this->options['concurrency']); $this->dispatch(self::BEFORE_MULTIPART_BUILD, array('builder' => $builder, 'file' => $file)); return $builder->build(); } return $this->options['client']->getCommand('PutObject', array('Bucket' => $this->options['bucket'], 'Key' => $key, 'Body' => $body, $aclType => $acl)); }
/** * @param \SplFileInfo $file */ public function __construct(\SplFileInfo $file) { if (!$file->isDir()) { throw new \InvalidArgumentException('Expecting directory'); } $this->iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file->getPathname(), \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS)); }
/** * Get file resource. * * @return resource */ protected function getFile() { if (!$this->file) { $this->file = fopen($this->fileInfo->getPathname(), 'a'); } return $this->file; }
private function getFileRelativePathname(\SplFileInfo $file) { if ($file instanceof SymfonySplFileInfo) { return $file->getRelativePathname(); } return $file->getPathname(); }
/** * Check if the file must be accepted, or not * * @param \SplFileInfo $archive * @return bool */ public function validate(\SplFileInfo $archive) { $zip = new \ZipArchive(); $pathname = $archive->getPathname(); $result = new ValidationResult(); $open = $zip->open($pathname, \ZipArchive::CHECKCONS); if (true === $open) { $result->setValid(true); } else { switch ((int) $open) { case \ZipArchive::ER_NOZIP: $result->setMessage('Not a zip archive:' . $pathname); break; case \ZipArchive::ER_INCONS: $result->setMessage('Zip archive inconsistent:' . $pathname); break; case \ZipArchive::ER_CRC: $result->setMessage('CRC error:' . $pathname); break; case \ZipArchive::ER_OPEN: $result->setMessage('Can\'t open file:' . $pathname); break; } } return $result; }