/** * @see ContentModifierInterface::modify() */ public function modify(SplFileInfo $generatedFile, array $data, Inflector $inflector, SplFileInfo $templateFile) { $options = $this->resolver->resolve($data); // retrieve target location $targetConfigFilepath = $this->resolveTargetFilePath($options['target'], $generatedFile->getPath()); $emBundleDefinition = sprintf(' %s: type: yml dir: %s prefix: %s alias: %s ', $options['bundle'], $options['relative_schema_directory'], $options['prefix'], $options['alias']); $configsFile = new SplFileInfo($targetConfigFilepath, '', ''); $configsContent = $configsFile->getContents(); // are configs not already registered ? if (strpos($configsContent, trim($emBundleDefinition)) !== false) { $this->logger->debug(sprintf('Config file "%s" is already registered into "%s". Abording.', $generatedFile->getFilename(), $targetConfigFilepath)); return $generatedFile->getContents(); } $this->filesystem->dumpFile($configsFile->getPathname(), str_replace(sprintf(' entity_managers: %s: mappings:', $options['em']), sprintf(' entity_managers: %s: mappings:%s', $options['em'], $emBundleDefinition), $configsContent)); $this->logger->info(sprintf('file updated : %s', $configsFile->getPathname())); return $generatedFile->getContents(); }
public function put($src, $dest) { if (false === file_exists($src)) { throw new \InvalidArgumentException(sprintf('Resource \'%s\' does not exist', $src)); } if (is_file($src) && is_dir($dest)) { $dest = $dest . DIRECTORY_SEPARATOR . basename($src); } if (is_file($src)) { $file = new \SplFileInfo($src); $this->dispatcher->dispatch(TransporterEvents::TRANSPORTER_PUT, new TransporterEvent($this, array('dest' => $dest, 'src' => $file->getPathname()))); $pwd = dirname($dest); if (!is_dir($pwd)) { $this->mkdir($pwd); } copy($file->getPathname(), $dest); } else { if (!$this->exists($dest)) { $this->mkdir($dest); } $finder = new Finder(); $test = $finder->in($src)->depth('== 0'); foreach ($test as $file) { $this->put(rtrim($src, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file->getFilename(), rtrim($dest, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file->getFilename()); } } }
private function processFile(SplFileInfo $path) { $relativeDirName = dirname(str_replace($this->inPath, '', $path->getPathname())); $filenameParts = explode('/', $relativeDirName); $pdfDir = array_pop($filenameParts); $restaurant = array_pop($filenameParts); $outDir = $this->outPath . '/' . $relativeDirName; if (!is_dir($outDir)) { mkdir($outDir, 0777, true); } $outFilename = $outDir . '/' . str_replace('.pdf', '-%03d.png', $path->getFilename()); $convertCommand = "gm convert -density 300 \"{$path->getPathname()}\" -resize '1280x1280>' +profile '*' +adjoin \"{$outFilename}\""; $this->output->writeln("Processing {$path->getPathname()}"); // convert directory exec($convertCommand); // create csv file $finder = new Finder(); $finder->files()->name('*.png')->in($outDir); /** @type SplFileInfo $file */ $index = 1; $this->output->writeln("-- " . $finder->count() . " images"); foreach ($finder as $file) { if (!isset($this->outCsv[$restaurant])) { $this->outCsv[$restaurant] = []; } $this->outCsv[$restaurant][] = ['restaurant' => $restaurant, 'pdf' => $path->getRelativePathname(), 'page' => $index, 'image' => $relativeDirName . '/' . $file->getFilename(), 'folder' => $relativeDirName]; $index++; } }
/** * @param \Symfony\Component\Finder\SplFileInfo $fileInfo * * @throws \Exception * * @return array */ private function getClassNameParts(SplFileInfo $fileInfo) { $pathParts = explode(DIRECTORY_SEPARATOR, $fileInfo->getPathname()); $sourceDirectoryPosition = array_search('src', $pathParts); if ($sourceDirectoryPosition) { return array_slice($pathParts, $sourceDirectoryPosition + 1); } $testsDirectoryPosition = array_search('tests', $pathParts); if ($testsDirectoryPosition) { return array_slice($pathParts, $testsDirectoryPosition + 2); } throw new \Exception(sprintf('Could not extract class name parts from file "%s".', $fileInfo->getPathname())); }
/** * @param \Symfony\Component\Finder\SplFileInfo $composerJsonFile * * @return void */ protected function updateComposerJsonFile(SplFileInfo $composerJsonFile) { exec('./composer.phar validate ' . $composerJsonFile->getPathname(), $output, $return); if ($return !== 0) { throw new \RuntimeException('Invalid composer file ' . $composerJsonFile->getPathname() . ': ' . print_r($output, true)); } $composerJson = json_decode($composerJsonFile->getContents(), true); $composerJson = $this->updater->update($composerJson, $composerJsonFile); $composerJson = $this->clean($composerJson); $composerJson = json_encode($composerJson, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); $composerJson = preg_replace(self::REPLACE_4_WITH_2_SPACES, '$1', $composerJson) . PHP_EOL; file_put_contents($composerJsonFile->getPathname(), $composerJson); }
/** * Create sprite image data holder * @param string $path * @param SplFileInfo $fileInfo */ public function __construct($path, SplFileInfo $fileInfo) { $this->basePath = $path; $this->info = $fileInfo; // Assign fileinfo variables $this->path = $this->info->getPathname(); $this->size = $this->info->getSize(); // Assign image data $info = getimagesize($this->path); if (!is_array($info)) { throw new UnexpectedValueException("The image '{$this->path}' is not a correct image format."); } $this->hash = sha1(file_get_contents($this->getFullPath())); $this->width = (int) $info[0]; $this->height = (int) $info[1]; $this->mime = $info['mime']; $this->type = explode('/', $this->mime)[1]; // Assign css name $ext = $this->info->getExtension(); // Replace path parts with `-` $name = str_replace(['/', '\\', '_'], '-', $this->info->getRelativePathname()); // Remove leading `-` $name = preg_replace('~^-*~', '', $name); // Remove double dashes $name = preg_replace('~-+~', '-', $name); // Remove file extension $name = preg_replace("~\\.{$ext}\$~", '', $name); // Replace dots with - $name = preg_replace('~\\.~', '-', $name); $this->name = $name; }
/** * Because SplFileInfo can't be serialized, we need to replace it with data that can be recovered when we serialize * this object again. * * @return array */ public function __sleep() { $fileInfo = ['file' => $this->file->getPathname(), 'relativePath' => $this->file->getRelativePath(), 'relativePathname' => $this->file->getRelativePathname()]; $classVars = get_object_vars($this); $this->file = $fileInfo; return array_keys($classVars); }
/** * Get the configuration file nesting path. * * @param \Symfony\Component\Finder\SplFileInfo $file * @return string */ private function getConfigurationNesting(SplFileInfo $file) { $directory = dirname($file->getPathname()); if ($tree = trim(str_replace(config_path(), '', $directory), DIRECTORY_SEPARATOR)) { $tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.'; } return $tree; }
/** * @param array $composerJson * @param \Symfony\Component\Finder\SplFileInfo $composerJsonFile * * @return array */ protected function updateAutoloadForTests(array $composerJson, SplFileInfo $composerJsonFile) { $testDirectoryKeys = $this->buildTestDirectoryKeys(); $bundlePath = dirname($composerJsonFile->getPathname()); foreach ($testDirectoryKeys as $testDirectoryKey) { $composerJson = $this->updateAutoload($composerJson, $testDirectoryKey, $bundlePath); } return $composerJson; }
function it_searches_for_files(FinderFactoryInterface $finderFactory, Finder $finder, SplFileInfo $firstSplFileInfo, SplFileInfo $secondSplFileInfo) { $finderFactory->create()->willReturn($finder); $finder->name('readme.md')->shouldBeCalled()->willReturn($finder); $finder->in(['/search/path/'])->shouldBeCalled()->willReturn($finder); $finder->ignoreUnreadableDirs()->shouldBeCalled()->willReturn($finder); $finder->files()->shouldBeCalled()->willReturn($finder); $finder->getIterator()->willReturn(new \ArrayIterator([$firstSplFileInfo->getWrappedObject(), $secondSplFileInfo->getWrappedObject()])); $finder->count()->willReturn(2); $firstSplFileInfo->getPathname()->willReturn('/search/path/nested1/readme.md'); $secondSplFileInfo->getPathname()->willReturn('/search/path/nested2/readme.md'); $this->locateFilesNamed('readme.md')->shouldReturn(['/search/path/nested1/readme.md', '/search/path/nested2/readme.md']); }
public function updateContent(SplFileInfo $fileInfo) { $pathname = $this->getAttribute('pathname'); $process = new Process("diff {$pathname} {$fileInfo->getPathname()}", storage_path('pigeon')); $process->run(); $output = $process->getOutput(); preg_match_all('/^>\\s*(.*)/mix', $output, $matches); if ($matches) { $newText = implode("\n", $matches[1]); app('files')->append(storage_path('pigeon') . '/' . $pathname, "\n" . $newText); $this->setAttribute('modified_at', $fileInfo->getMTime()); } }
/** * @see ContentModifierInterface::modify() */ public function modify(SplFileInfo $generatedFile, array $data, Inflector $inflector, SplFileInfo $templateFile) { $options = $this->resolver->resolve($data); $fileContent = $generatedFile->getContents(); // current file is a bundle ? $isInBundle = preg_match(sprintf('/namespace (.*%s.*Bundle);/', $inflector->translate('MajoraNamespace')), $fileContent, $inBundleMatches); $isABundle = preg_match(sprintf('/class (([\\w]*)%s[\\w]*Bundle) extends [\\w]*Bundle/', $inflector->translate('MajoraNamespace')), $fileContent, $isBundleMatches); if (!$isInBundle || !$isABundle) { $this->logger->notice(sprintf('Try to register "%s" file into Kernel which isnt a bundle. Abording.', $generatedFile->getFilename())); return $fileContent; } $bundleInclusion = sprintf('new %s\\%s(),', $inBundleMatches[1], $isBundleMatches[1]); $kernelFile = new SplFileInfo(sprintf('%s/%s', $this->kernelDir, $options['kernel_filename']), '', ''); $kernelContent = $kernelFile->getContents(); // is bundle not already registered ? if (strpos($kernelContent, $bundleInclusion) !== false) { $this->logger->debug(sprintf('Bundle "%s" is already registered. Abording.', $generatedFile->getFilename())); return $fileContent; } $this->filesystem->dumpFile($kernelFile->getPathname(), preg_replace('/(Bundle\\(\\)\\,)(\\n[\\s]+\\);)/', sprintf("\$1\n %s\$2", $bundleInclusion), $kernelContent)); $this->logger->info(sprintf('file updated : %s', $kernelFile->getPathname())); return $fileContent; }
public function import(\Symfony\Component\Finder\SplFileInfo $file, $force = false) { $this->validateLoaders($this->loaders); $filename = $file->getFilename(); list($domain, $locale, $extension) = explode('.', $filename); if (!isset($this->loaders[$extension]) || !$this->loaders[$extension] instanceof \Symfony\Component\Translation\Loader\LoaderInterface) { throw new \Exception(sprintf('Requested loader for extension .%s isnt set', $extension)); } $loader = $this->loaders[$extension]; $messageCatalogue = $loader->load($file->getPathname(), $locale, $domain); $importedTranslations = 0; foreach ($messageCatalogue->all($domain) as $keyword => $text) { if ($this->importSingleTranslation($keyword, $text, $locale, $filename, $domain, $force)) { $importedTranslations++; } } return $importedTranslations; }
/** * @param \Symfony\Component\Finder\SplFileInfo $fileInfo * * @return void */ public function addDependencies(SplFileInfo $fileInfo) { $content = $fileInfo->getContents(); $_SERVER['argv'] = []; if (!defined('STDIN')) { define('STDIN', fopen(__FILE__, 'r')); } $file = new \PHP_CodeSniffer_File($fileInfo->getPathname(), [], [], new \PHP_CodeSniffer()); $file->start($content); $tokens = $file->getTokens(); $pointer = 0; $classNames = []; while ($foundPosition = $file->findNext([T_NEW, T_USE, T_DOUBLE_COLON], $pointer)) { $pointer = $foundPosition + 1; $currentToken = $tokens[$foundPosition]; if ($currentToken['type'] === 'T_NEW' || $currentToken['type'] === 'T_USE') { $pointer = $foundPosition + 2; $endOfNew = $file->findNext([T_SEMICOLON, T_OPEN_PARENTHESIS, T_WHITESPACE, T_DOUBLE_COLON], $pointer); $classNameParts = array_slice($tokens, $pointer, $endOfNew - $foundPosition - 2); $classNames[] = $this->buildClassName($classNameParts); } if ($currentToken['type'] === 'T_DOUBLE_COLON') { $pointer = $foundPosition + 1; $startOf = $file->findPrevious([T_OPEN_PARENTHESIS, T_WHITESPACE, T_OPEN_SQUARE_BRACKET], $foundPosition - 1) + 1; $classNameParts = array_slice($tokens, $startOf, $foundPosition - $startOf); $classNames[] = $this->buildClassName($classNameParts); } } $classNames = array_unique($classNames); foreach ($classNames as $className) { $className = ltrim($className, '\\'); if (strpos($className, '_') === false && strpos($className, '\\') === false) { continue; } if (strpos($className, 'Spryker') !== false || strpos($className, 'Generated') !== false || strpos($className, 'Orm') !== false || strpos($className, 'static') !== false || strpos($className, 'self') !== false) { continue; } $dependencyInformation[DependencyTree::META_FOREIGN_LAYER] = 'external'; $dependencyInformation[DependencyTree::META_FOREIGN_CLASS_NAME] = $className; $dependencyInformation[DependencyTree::META_FOREIGN_IS_EXTERNAL] = true; $this->addDependency($fileInfo, 'external', $dependencyInformation); } $this->cleanAutoloader(); }
/** * Impoort the given file and return the number of inserted translations. * * @param \Symfony\Component\Finder\SplFileInfo $file * @param boolean $forceUpdate force update of the translations * @return int */ public function import(\Symfony\Component\Finder\SplFileInfo $file, $forceUpdate = false) { $imported = 0; list($domain, $locale, $extention) = explode('.', $file->getFilename()); if (isset($this->loaders[$extention])) { $messageCatalogue = $this->loaders[$extention]->load($file->getPathname(), $locale, $domain); $translationFile = $this->fileManager->getFor($file->getFilename(), $file->getPath()); foreach ($messageCatalogue->all($domain) as $key => $content) { // skip empty translation values if (!isset($content)) { continue; } $transUnit = $this->storage->getTransUnitByKeyAndDomain($key, $domain); if (!$transUnit instanceof TransUnitInterface) { $transUnit = $this->transUnitManager->create($key, $domain); } $translation = $this->transUnitManager->addTranslation($transUnit, $locale, $content, $translationFile); if ($translation instanceof TranslationInterface) { $imported++; } else { if ($forceUpdate) { $translation = $this->transUnitManager->updateTranslation($transUnit, $locale, $content); $imported++; } } // convert MongoTimestamp objects to time to don't get an error in: // Doctrine\ODM\MongoDB\Mapping\Types\TimestampType::convertToDatabaseValue() if ($transUnit instanceof TransUnitDocument) { $transUnit->convertMongoTimestamp(); } } $this->storage->flush(); // clear only Lexik entities foreach (array('file', 'trans_unit', 'translation') as $name) { $this->storage->clear($this->storage->getModelClass($name)); } } else { throw new \RuntimeException(sprintf('No load found for "%s" format.', $extention)); } return $imported; }
/** * Constructor. * * @param null|SplFileInfo $file */ public function __construct(SplFileInfo $file = null) { $this->file = $file; if ($this->file instanceof SplFileInfo) { // file extension: "md" $this->fileExtension = pathinfo($this->file, PATHINFO_EXTENSION); // file path: "Blog" $this->filePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath()); // file id: "Blog/Post 1" $this->fileId = ($this->filePath ? $this->filePath . '/' : '') . basename($this->file->getBasename(), '.' . $this->fileExtension); /* * variables default values */ // id - ie: "blog/post-1" $this->id = $this->urlize($this->fileId); // pathname - ie: "blog/post-1" $this->pathname = $this->urlize($this->fileId); // path - ie: "blog" $this->path = $this->urlize($this->filePath); // name - ie: "post-1" $this->name = $this->urlize(basename($this->file->getBasename(), '.' . $this->fileExtension)); /* * front matter default values */ // title - ie: "Post 1" $this->setTitle(basename($this->file->getBasename(), '.' . $this->fileExtension)); // section - ie: "blog" $this->setSection(explode('/', $this->path)[0]); // date $this->setDate(filemtime($this->file->getPathname())); // permalink $this->setPermalink($this->pathname); parent::__construct($this->id); } else { $this->virtual = true; parent::__construct(); } }
/** * Loads a plugin config file and merges it to plugin config * * @param string $magentoRootFolder * @param SplFileInfo $file */ protected function registerPluginConfigFile($magentoRootFolder, $file) { if (BinaryString::startsWith($file->getPathname(), 'vfs://')) { $path = $file->getPathname(); } else { $path = $file->getRealPath(); if ($path === "") { throw new \UnexpectedValueException(sprintf("Realpath for '%s' did return an empty string.", $file)); } if ($path === false) { $this->log(sprintf("<error>Plugin config file broken link '%s'</error>", $file)); return; } } $this->logDebug('Load plugin config <comment>' . $path . '</comment>'); $localPluginConfigFile = ConfigFile::createFromFile($path); $localPluginConfigFile->applyVariables($magentoRootFolder, $file); $this->_pluginConfig = $localPluginConfigFile->mergeArray($this->_pluginConfig); }
/** * @return string */ public function key() { return $this->current->getPathname(); }
/** * @param \Symfony\Component\Finder\SplFileInfo $file * @param string $methodPattern * * @return string */ private function buildMethodTagFromFile(SplFileInfo $file, $methodPattern) { $className = $this->replaceProjectPath($file->getPathname()); $className = $this->replaceVendorPath($className); $className = str_replace(['/', '.php'], ['\\', ''], $className); return ' * ' . str_replace(self::PLACEHOLDER_CLASS_NAME, $className, $methodPattern); }
/** * Loads a plugin config file and merges it to plugin config * * @param string $magentoRootFolder * @param SplFileInfo $file */ protected function registerPluginConfigFile($magentoRootFolder, $file) { if (String::startsWith($file->getPathname(), 'vfs://')) { $path = $file->getPathname(); } else { $path = $file->getRealPath(); } if (OutputInterface::VERBOSITY_DEBUG <= $this->_output->getVerbosity()) { $this->_output->writeln('<debug>Load plugin config <comment>' . $path . '</comment></debug>'); } $localPluginConfig = \file_get_contents($path); $localPluginConfig = Yaml::parse($this->applyVariables($localPluginConfig, $magentoRootFolder, $file)); $this->_pluginConfig = ArrayFunctions::mergeArrays($this->_pluginConfig, $localPluginConfig); }
function it_should_filter_by_a_list_of_files(SplFileInfo $file1, SplFileInfo $file2) { $file1->getPathname()->willReturn('path1/file.php'); $file2->getPathname()->willReturn('path2/file.php'); $iterator = new \ArrayIterator(array($file1->getWrappedObject())); $result = $this->filterByFileList($iterator); $result->count()->shouldBe(1); $files = $result->toArray(); $files[0]->shouldBe($file1); }
/** * Loads a plugin config file and merges it to plugin config * * @param string $magentoRootFolder * @param SplFileInfo $file */ protected function registerPluginConfigFile($magentoRootFolder, $file) { if (BinaryString::startsWith($file->getPathname(), 'vfs://')) { $path = $file->getPathname(); } else { $path = $file->getRealPath(); if ($path === "") { throw new \UnexpectedValueException(sprintf("Realpath for '%s' did return an empty string.", $file)); } if ($path === false) { $this->_output->writeln(sprintf("<error>Plugin config file broken link '%s'</error>", $file)); return; } } if (OutputInterface::VERBOSITY_DEBUG <= $this->_output->getVerbosity()) { $this->_output->writeln('<debug>Load plugin config <comment>' . $path . '</comment></debug>'); } $localPluginConfig = \file_get_contents($path); $localPluginConfig = Yaml::parse($this->applyVariables($localPluginConfig, $magentoRootFolder, $file)); $this->_pluginConfig = ArrayFunctions::mergeArrays($this->_pluginConfig, $localPluginConfig); }
private function isBinary(SplFileInfo $file) { $fileInfo = new FileInfo($file->getPathname(), $this->params['text_extensions']); return false === $fileInfo->hasPredefinedExtension(); }
function it_silences_finder_exceptions_even_if_searching_in_multiple_sources(FinderFactoryInterface $finderFactory, Finder $firstFinder, Finder $secondFinder, SplFileInfo $splFileInfo) { $this->beConstructedWith($finderFactory, ['/search/path/first/', '/search/path/second/']); $finderFactory->create()->willReturn($firstFinder, $secondFinder); $firstFinder->name('readme.md')->shouldBeCalled()->willReturn($firstFinder); $firstFinder->in('/search/path/first/')->shouldBeCalled()->willReturn($firstFinder); $firstFinder->ignoreUnreadableDirs()->shouldBeCalled()->willReturn($firstFinder); $firstFinder->files()->shouldBeCalled()->willReturn($firstFinder); $secondFinder->name('readme.md')->shouldBeCalled()->willReturn($secondFinder); $secondFinder->in('/search/path/second/')->shouldBeCalled()->willReturn($secondFinder); $secondFinder->ignoreUnreadableDirs()->shouldBeCalled()->willReturn($secondFinder); $secondFinder->files()->shouldBeCalled()->willReturn($secondFinder); $firstFinder->getIterator()->willReturn(new \ArrayIterator([$splFileInfo->getWrappedObject()])); $secondFinder->getIterator()->willThrow(\InvalidArgumentException::class); $splFileInfo->getPathname()->willReturn('/search/path/first/nested/readme.md'); $this->locateFilesNamed('readme.md')->shouldReturn(['/search/path/first/nested/readme.md']); }
/** * @param \Symfony\Component\Finder\SplFileInfo $file * * @return string */ private function getPath(SplFileInfo $file) { switch ($file->getExtension()) { case 'gz': $path = 'compress.zlib://' . $file->getPathname(); break; case 'bz2': $path = 'compress.bzip2://' . $file->getPathname(); break; default: $path = $file->getPathname(); break; } return $path; }
/** * @param string|null $code * @param SplFileInfo $file * @param string $suffix * * @return string|null */ private function determineCode($code, SplFileInfo $file, $suffix) { if (null !== $code) { return $code; } $candidateFile = new SplFileInfo($file->getPathname() . $suffix, '', ''); if ($candidateFile->isFile()) { return $candidateFile->getContents(); } }
/** * @param SplFileInfo $file * * @return self */ public static function create(SplFileInfo $file) { return new static($file->getPathname(), $file->getRelativePath(), $file->getRelativePathname()); }
/** * Move a single file or folder. * * @param SplFileInfo $file The file to move. * * @param string $targetDir The destination directory. * * @param bool $logging Flag determining if actions shall get logged. * * @param IOInterface $ioHandler The io handler to log to. * * @return void * * @throws \RuntimeException When an unknown file type has been encountered. */ private function moveFile(SplFileInfo $file, $targetDir, $logging, $ioHandler) { $pathName = $file->getPathname(); $destinationFile = str_replace($this->tempDir, $targetDir, $pathName); // Symlink must(!) be handled first as the isDir() and isFile() checks return true for symlinks. if ($file->isLink()) { $target = $file->getLinkTarget(); if ($logging) { $ioHandler->write(sprintf('link %s to %s', $target, $destinationFile)); } symlink($target, $destinationFile); unlink($pathName); return; } if ($file->isDir()) { $permissions = substr(decoct(fileperms($pathName)), 1); $this->folders[] = $pathName; if (!is_dir($destinationFile)) { if ($logging) { $ioHandler->write(sprintf('mkdir %s (permissions: %s)', $pathName, $permissions)); } mkdir($destinationFile, octdec($permissions), true); } return; } if ($file->isFile()) { $permissions = substr(decoct(fileperms($pathName)), 1); if ($logging) { $ioHandler->write(sprintf('move %s to %s (permissions: %s)', $pathName, $destinationFile, $permissions)); } copy($pathName, $destinationFile); chmod($destinationFile, octdec($permissions)); unlink($pathName); return; } throw new \RuntimeException(sprintf('Unknown file of type %s encountered for %s', filetype($pathName), $pathName)); }
/** * Get ID3 info from a file. * * @param SplFileInfo $file * * @return array|null */ public function getInfo(SplFileInfo $file) { $info = $this->getID3->analyze($file->getPathname()); if (isset($info['error'])) { return; } // Copy the available tags over to comment. // This is a helper from getID3, though it doesn't really work well. // We'll still prefer getting ID3v2 tags directly later. // Read on. getid3_lib::CopyTagsToComments($info); $props = ['artist' => '', 'album' => '', 'title' => '', 'length' => $info['playtime_seconds'], 'lyrics' => '', 'cover' => array_get($info, 'comments.picture', [null])[0], 'path' => $file->getPathname(), 'mtime' => $file->getMTime()]; if (!($comments = array_get($info, 'comments_html'))) { return $props; } // We prefer id3v2 tags over others. if (!($artist = array_get($info, 'tags.id3v2.artist', [null])[0])) { $artist = array_get($comments, 'artist', [''])[0]; } if (!($album = array_get($info, 'tags.id3v2.album', [null])[0])) { $album = array_get($comments, 'album', [''])[0]; } if (!($title = array_get($info, 'tags.id3v2.title', [null])[0])) { $title = array_get($comments, 'title', [''])[0]; } if (!($lyrics = array_get($info, 'tags.id3v2.unsynchronised_lyric', [null])[0])) { $lyrics = array_get($comments, 'unsynchronised_lyric', [''])[0]; } $props['artist'] = trim($artist); $props['album'] = trim($album); $props['title'] = trim($title); $props['lyrics'] = trim($lyrics); return $props; }
/** * Returns the parent directory name of the file * * @return string */ protected function getParentDirname() { return basename(dirname($this->file->getPathname())); }