sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function dump($file, $contents) { $filesystem = new Filesystem(); $filesystem->dumpFile($file, $contents); $filesystem->chmod($file, 0644); }
Write the config file contents out to the config file. @param string $file File path @param string $contents Config file contents
entailment
public function compare($string) { foreach ($this->tokens as $token) { if ($token->hasTokenBeenFound()) { continue; } $token->compare($string); } }
Given some string, see if it matches any of our tokens. @param string $string
entailment
public function compareStart($string) { foreach ($this->tokens as $token) { if ($token->hasTokenBeenFound()) { continue; } $token->compareStart($string); } }
See if the beginning of the passed string matches any of our token(s). @param string $string
entailment
protected function isCacheExpired($fromCurrency, $toCurrency) { $cacheCreationTime = $this->getCacheCreationTime($fromCurrency, $toCurrency); return (time() - $cacheCreationTime) > $this->getCacheTimeOut()->format('%s'); }
Checks if cache is expired @param string $fromCurrency @param string $toCurrency @return bool
entailment
public function start($message, $maxSteps) { $this->info($message); if ($this->progressBar instanceof ProgressBar) { $this->progressBar->setMessage($message); $this->progressBar->start($maxSteps); } }
Starting the install process. @param string $message Start message @param int $maxSteps The number of steps that will be taken
entailment
public function step($message) { ++$this->stepCount; $this->info($message); if ($this->progressBar instanceof ProgressBar) { $this->progressBar->setMessage($message); $this->progressBar->advance(); } }
Signify the move to the next step in the install. @param string $message Very short message about the step
entailment
public function end($message) { $this->info($message); if ($this->progressBar instanceof ProgressBar) { $this->progressBar->setMessage($message); $this->progressBar->finish(); } }
Ending the install process. @param string $message End message
entailment
public function debug($message, array $context = []) { if ($this->logger instanceof LoggerInterface) { $this->logger->debug($message, $context); } }
Log a message, shown in highest verbosity mode. @param string $message @param array $context
entailment
public function setCachePath($cachePath) { if (!is_dir($cachePath)) { throw new Exception\CachePathNotFoundException(sprintf('Cache Path, %s does not exists', $cachePath)); } $this->cachePath = $cachePath; return $this; }
Sets cachePath @param string $cachePath @throws Exception\CachePathNotFoundException @return self
entailment
public function cacheExists($fromCurrency, $toCurrency) { $cacheFile = $this->getCacheFileLocation($fromCurrency, $toCurrency); if (!is_readable($cacheFile)) { return false; } return !$this->isCacheExpired($fromCurrency, $toCurrency); }
{@inheritDoc}
entailment
public function createCache($fromCurrency, $toCurrency, $rate) { $cacheFile = $this->getCacheFileLocation($fromCurrency, $toCurrency); if (!file_exists($cacheFile)) { touch($cacheFile); } file_put_contents($cacheFile, $rate); }
{@inheritDoc}
entailment
public function activate(Composer $composer, IOInterface $inputOutput) { if ($composer->getPackage()->getType() !== 'project') { $this->isProject = false; $inputOutput->writeError( 'Root package is not of type "project", we will not installing Contao extensions.' ); return; } $this->composer = $composer; if (null === $this->runonceManager) { $rootDir = getcwd() . '/'; $extras = $composer->getPackage()->getExtra(); if (isset($extras['symfony-app-dir']) && is_dir($rootDir . $extras['symfony-app-dir'])) { $rootDir .= trim($extras['symfony-app-dir'], '/'); } else { $rootDir .= 'app'; } $this->runonceManager = new RunonceManager( $rootDir . '/Resources/contao/config/runonce.php' ); } $installationManager = $composer->getInstallationManager(); $installationManager->addInstaller( new ContaoModuleInstaller($this->runonceManager, $inputOutput, $composer) ); $installationManager->addInstaller( new LegacyContaoModuleInstaller($this->runonceManager, $inputOutput, $composer) ); }
{@inheritDoc}
entailment
public function filterClassNames(array $statements) { $names = []; foreach ($this->filterClasses($statements) as $class) { $names[] = $class->name; } foreach ($this->filterNamespaces($statements) as $namespace) { foreach ($this->filterClasses($namespace->stmts) as $class) { $names[] = $namespace->name.'\\'.$class->name; } } return $names; }
Returns class names, including those within namespaces (one level deep). @param array $statements @return array
entailment
public function findFirstVariableAssignment(array $statements, $name, $notFoundError = null) { foreach ($this->filterAssignments($statements) as $assign) { if ($assign->var instanceof Variable && $assign->var->name === $name) { return $assign; } } throw new \RuntimeException($notFoundError ?: sprintf('Variable assignment $%s not found', $name)); }
Find first variable assignment with a given name. @param array $statements @param string $name @param string|null $notFoundError @return Assign
entailment
public function findFirstPropertyFetchAssignment(array $statements, $variable, $property, $notFoundError = null) { foreach ($this->filterAssignments($statements) as $assign) { if (!$assign->var instanceof PropertyFetch) { continue; } if ($assign->var->name !== $property) { continue; } $var = $assign->var->var; if ($var instanceof Variable && $var->name === $variable) { return $assign; } } throw new \RuntimeException($notFoundError ?: sprintf('Variable assignment $%s->%s not found', $variable, $property)); }
Find first property fetch assignment with a given name. EG: Find $foo->bar = something. @param array $statements PHP statements @param string $variable The variable name, EG: foo in $foo->bar @param string $property The property name, EG: bar in $foo->bar @param string|null $notFoundError Use this error when not found @return Assign
entailment
public function arrayStringKeys(Array_ $array) { $keys = []; foreach ($array->items as $item) { if ($item->key instanceof String_) { $keys[] = $item->key->value; } } return $keys; }
Given an array, find all the string keys. @param Array_ $array @return array
entailment
public function add(AbstractInstaller $installer) { $installer->setOutput($this->output); $this->installers[] = $installer; }
Add an installer. @param AbstractInstaller $installer
entailment
public function mergeEnv() { $env = []; foreach ($this->installers as $installer) { $env = array_merge($env, $installer->getEnv()); } return $env; }
Merge the environment variables from all installers. @return array
entailment
public function sumStepCount() { $sum = 0; foreach ($this->installers as $installer) { $sum += $installer->stepCount(); } return $sum; }
Get the total number of steps from all installers. @return int
entailment
private function getConsolePath() { if (file_exists($this->rootDir . '/app/console')) { return $this->rootDir . '/app/console'; } $finder = new Finder(); $files = $finder->files()->depth(1)->name('console')->in($this->rootDir); /** @var SplFileInfo $file */ foreach ($files as $file) { return $file->getPathname(); } throw new \UnderflowException('Symfony console application was not found.'); }
Find path to console application @return string @throws \UnderflowException If console application was not found.
entailment
public function resolve($name) { if (!$this->hasStandard($name)) { throw new \InvalidArgumentException('Unknown coding standard: '.$name); } foreach ($this->standards[$name] as $location) { if (file_exists($location)) { return $location; } } throw new \RuntimeException(sprintf('Failed to find the \'%s\' coding standard, likely need to run Composer install', $name)); }
Find the location of a standard. @param string $name The standard name @return string
entailment
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { if (false === parent::isInstalled($repo, $package)) { return false; } $targetRoot = $this->getContaoRoot(); foreach ($this->getSources($package) as $targetPath) { if (!file_exists($this->filesystem->normalizePath($targetRoot . '/' . $targetPath))) { return false; } } return true; }
Make sure symlinks/directories exist, otherwise consider a package uninstalled so they are being regenerated. {@inheritDoc}
entailment
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $this->logVerbose(sprintf('Installing Contao sources for %s', $package->getName())); parent::install($repo, $package); $this->addSymlinks($package, $this->getContaoRoot(), $this->getSources($package)); $this->addCopies($package, $this->getFilesRoot(), $this->getUserFiles($package), self::DUPLICATE_IGNORE); $this->addRunonces($package, $this->getRunonces($package)); $this->logVerbose(''); }
Add symlinks for Contao sources after installing a package. {@inheritdoc}
entailment
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { if (!$repo->hasPackage($initial)) { throw new \InvalidArgumentException('Package is not installed: '.$initial); } $this->logVerbose(sprintf('Updating Contao sources for %s', $initial->getName())); $contaoRoot = $this->getContaoRoot(); $this->removeSymlinks($initial, $contaoRoot, $this->getSources($initial)); parent::update($repo, $initial, $target); $this->addSymlinks($target, $contaoRoot, $this->getSources($target)); $this->addCopies($target, $this->getFilesRoot(), $this->getUserFiles($target), self::DUPLICATE_IGNORE); $this->addRunonces($target, $this->getRunonces($target)); $this->logVerbose(''); }
Remove symlinks for Contao sources before update, then add them again afterwards. {@inheritdoc} @throws \InvalidArgumentException When the requested package is not installed.
entailment
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { if (!$repo->hasPackage($package)) { throw new \InvalidArgumentException('Package is not installed: '.$package); } $this->logVerbose(sprintf('Removing Contao sources for %s', $package->getName())); $this->removeSymlinks($package, $this->getContaoRoot(), $this->getSources($package)); parent::uninstall($repo, $package); $this->logVerbose(''); }
Remove symlinks for Contao sources before uninstalling a package. {@inheritdoc} @throws \InvalidArgumentException When the requested package is not installed.
entailment
protected function addSymlinks(PackageInterface $package, $targetRoot, array $pathMap, $mode = self::DUPLICATE_FAIL) { if (empty($pathMap)) { return; } $packageRoot = $this->getInstallPath($package); $actions = []; // Check the file map first and make sure nothing exists. foreach ($pathMap as $sourcePath => $targetPath) { $source = $this->filesystem->normalizePath($packageRoot . ($sourcePath ? ('/'.$sourcePath) : '')); $target = $this->filesystem->normalizePath($targetRoot . '/' . $targetPath); if ($this->canAddSymlink($source, $target, $mode)) { $actions[$source] = $target; } } // Only actually create the links if the checks are successful to prevent orphans. foreach ($actions as $source => $target) { $this->logSymlink($source, $target); $this->filesystem->ensureDirectoryExists(dirname($target)); if (Platform::isWindows()) { $success = @symlink($source, $target); } else { $success = $this->filesystem->relativeSymlink($source, $target); } if (!$success) { throw new \RuntimeException('Failed to create symlink ' . $target); } } }
Creates symlinks for a map of relative file paths. Key is the relative path to composer package, whereas "value" is relative to Contao root. @param PackageInterface $package The package being processed. @param string $targetRoot The target directory. @param array $pathMap The path mapping. @param int $mode The mode how to handle duplicate files. @return void @throws \RuntimeException When the symlink could not be created.
entailment
protected function removeSymlinks( PackageInterface $package, $targetRoot, array $pathMap, $mode = self::INVALID_FAIL ) { if (empty($pathMap)) { return; } $packageRoot = $this->getInstallPath($package); $actions = []; // Check the file map first and make sure we only remove our own symlinks. foreach ($pathMap as $sourcePath => $targetPath) { $source = $this->filesystem->normalizePath($packageRoot . ($sourcePath ? ('/'.$sourcePath) : '')); $target = $this->filesystem->normalizePath($targetRoot . '/' . $targetPath); if ($this->canRemoveSymlink($source, $target, $mode)) { $actions[] = $target; } } // Remove the symlinks if everything is ok. foreach ($actions as $target) { $this->logRemove($target); if (is_dir($target)) { $this->filesystem->removeDirectory($target); } else { $this->filesystem->unlink($target); } $this->removeEmptyDirectories(dirname($target), $targetRoot); } }
Removes symlinks from a map of relative file paths. Key is the relative path to composer package, whereas "value" is relative to Contao root. @param PackageInterface $package The package being processed. @param string $targetRoot The target directory. @param array $pathMap The path mapping. @param int $mode The mode how to handle duplicate files. @return void
entailment
protected function addCopies(PackageInterface $package, $targetRoot, array $pathMap, $mode = self::DUPLICATE_FAIL) { if (empty($pathMap)) { return; } $packageRoot = $this->getInstallPath($package); $actions = []; // Check the file map first and make sure nothing exists. foreach ($pathMap as $sourcePath => $targetPath) { $source = $this->filesystem->normalizePath($packageRoot . (empty($sourcePath) ? '' : ('/'.$sourcePath))); $target = $this->filesystem->normalizePath($targetRoot . '/' . $targetPath); if (!is_readable($source)) { throw new \RuntimeException( sprintf('Installation source "%s" does not exist', $sourcePath) ); } if (file_exists($target) && !$this->canAddTarget($target, $mode)) { continue; } $actions[$source] = $target; } // Only actually create the links if the checks are successful to prevent orphans. foreach ($actions as $source => $target) { $this->logCopy($source, $target); $this->copyRecursive($source, $target); } }
Creates copies for a map of relative file paths. Key is the relative path to composer package, whereas "value" is relative to Contao root. @param PackageInterface $package The package being processed. @param string $targetRoot The target directory. @param array $pathMap The path mapping. @param int $mode The mode how to handle duplicate files. @return void @throws \RuntimeException When a source path does not exist or is not readable.
entailment
protected function removeCopies($targetRoot, array $pathMap) { if (empty($pathMap)) { return; } $actions = []; // Check the file map first and make sure we only remove our own symlinks. foreach ($pathMap as $targetPath) { $target = $this->filesystem->normalizePath($targetRoot . '/' . $targetPath); if (!file_exists($target)) { continue; } $actions[] = $target; } // Remove the symlinks if everything is ok. foreach ($actions as $target) { $this->logRemove($target); $this->filesystem->unlink($target); $this->removeEmptyDirectories(dirname($target), $targetRoot); } }
Removes copies from a map of relative file paths. Key is the relative path to composer package, whereas "value" is relative to Contao root. @param string $targetRoot The target directory. @param array $pathMap The path mapping. @return void
entailment
protected function addRunonces(PackageInterface $package, array $files) { $rootDir = $this->getInstallPath($package); foreach ($files as $file) { $this->runonceManager->addFile($this->filesystem->normalizePath($rootDir . '/' . $file)); } }
Adds runonce files of a package to the RunonceManager instance. @param PackageInterface $package The package being processed. @param array $files The file names of all runonce files. @return void
entailment
private function copyRecursive($source, $target) { if (!is_dir($source)) { $this->filesystem->ensureDirectoryExists(dirname($target)); copy($source, $target); return; } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); $this->filesystem->ensureDirectoryExists($target); foreach ($iterator as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); if ($file->isDir()) { $this->filesystem->ensureDirectoryExists($targetPath); } else { copy($file->getPathname(), $targetPath); } } }
Recursive copy source file or directory to target path. @param string $source The source file or folder. @param string $target The target file or folder. @return void
entailment
private function removeEmptyDirectories($pathname, $root) { if (is_dir($pathname) && $pathname !== $root && $this->filesystem->isDirEmpty($pathname) ) { $this->filesystem->removeDirectory($pathname); if (!$this->removeEmptyDirectories(dirname($pathname), $root)) { if ($this->io->isVeryVerbose()) { $this->io->writeError(sprintf(' - Removing empty directory "%s"', $pathname)); } } return true; } return false; }
Clean up empty directories. @param string $pathname The path to remove if empty. @param string $root The path of the root installation. @return bool
entailment
private function canAddSymlink($source, $target, $mode) { if (!is_readable($source)) { throw new \RuntimeException( sprintf('Installation source "%s" does not exist or is not readable', $source) ); } if (file_exists($target)) { // Target link already exists and is correct, do nothing if (is_link($target) && $source === realpath($target)) { return false; } if (!$this->canAddTarget($target, $mode)) { return false; } } return true; }
Check if the source exists, is readable and shall get symlink'ed to the target. @param string $source The source path. @param string $target The target path. @param int $mode The duplicate file handling mode. @return bool @throws \RuntimeException When the source is not readable.
entailment
private function canRemoveSymlink($source, $target, $mode) { if (!file_exists($target)) { return false; } if (!is_link($target) || $this->filesystem->normalizePath($source) !== $this->filesystem->normalizePath(realpath($target)) ) { if (self::INVALID_IGNORE === $mode) { return false; } if (self::INVALID_FAIL === $mode) { throw new \RuntimeException( sprintf( '"%s" is not a link to "%s" (expected "%s" but got "%s")', $target, $source, $this->filesystem->normalizePath($source), $this->filesystem->normalizePath(realpath($target)) ) ); } } return true; }
Check if the target exists, is a symlink and the symlink points to the target and therefore shall get removed. @param string $source The source path. @param string $target The target path. @param int $mode The invalid file handling mode. @return bool @throws \RuntimeException When a file entry is not a symlink to the expected target and mode is INVALID_FAIL.
entailment
private function canAddTarget($target, $mode) { // Mode is set to ignore existing targets if ($mode === self::DUPLICATE_IGNORE) { return false; } // Error if we're not allowed to overwrite or can't remove the existing target if ($mode !== self::DUPLICATE_OVERWRITE || !$this->filesystem->remove($target)) { throw new \RuntimeException(sprintf('Installation target "%s" already exists', $target)); } return true; }
Checks if the target file should be added based on the given mode. @param string $target The target path. @param int $mode The overwrite mode. @return bool @throws \RuntimeException If target exists and can not or must not be removed.
entailment
public static function getCurrency($countryCode) { if (!array_key_exists($countryCode, self::$currencies)) { throw new Exception\InvalidArgumentException(sprintf('Unsupported Country Code, %s', $countryCode)); } return self::$currencies[$countryCode]; }
Gets Currency code by Country code @param string $countryCode Country code @return string @throws Exception\InvalidArgumentException
entailment
private function getContaoExtra(PackageInterface $package, $key) { $extras = $package->getExtra(); if (!isset($extras['contao']) || !isset($extras['contao'][$key])) { return null; } return $extras['contao'][$key]; }
Retrieves a value from the package extra "contao" section. @param PackageInterface $package The package to extract the section from. @param string $key The key to obtain from the extra section. @return mixed|null
entailment
public function runInstallation(InstallerCollection $installers) { $this->output->start('Starting install', $installers->sumStepCount() + 1); foreach ($installers->all() as $installer) { $installer->install(); } $this->output->end('Install completed'); }
Run the entire install process. @param InstallerCollection $installers
entailment
public function renderReport(Report $report) { $this->output->writeln(''); $groupByFile = []; /** @var RuleViolation $violation */ foreach ($report->getRuleViolations() as $violation) { $groupByFile[$violation->getFileName()][] = $violation; } /** @var ProcessingError $error */ foreach ($report->getErrors() as $error) { $groupByFile[$error->getFile()][] = $error; } foreach ($groupByFile as $file => $problems) { $violationCount = 0; $errorCount = 0; $table = new Table($this->output); $table->setStyle('borderless'); foreach ($problems as $problem) { if ($problem instanceof RuleViolation) { $table->addRow([$problem->getBeginLine(), '<comment>VIOLATION</comment>', $problem->getDescription()]); ++$violationCount; } if ($problem instanceof ProcessingError) { $table->addRow(['-', '<error>ERROR</error>', $problem->getMessage()]); ++$errorCount; } } $this->output->writeln([ sprintf('<fg=white;options=bold>FILE: %s</>', str_replace($this->basePath.'/', '', $file)), sprintf('<fg=white;options=bold>FOUND %d ERRORS AND %d VIOLATIONS</>', $errorCount, $violationCount), ]); $table->render(); $this->output->writeln(''); } }
This method will be called when the engine has finished the source analysis phase. @param \PHPMD\Report $report
entailment
public function initializeInstallOutput(OutputInterface $output) { $progressBar = null; if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERY_VERBOSE) { // Low verbosity, use progress bar. $progressBar = new ProgressBar($output); $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s% [%message%]'); } return new InstallOutput(new ConsoleLogger($output), $progressBar); }
@param OutputInterface $output @return InstallOutput
entailment
public function initializeInstallerFactory(InputInterface $input) { $validate = new Validate(); $resolver = new DatabaseResolver(); $pluginDir = realpath($validate->directory($input->getOption('plugin'))); $pluginsDir = $input->getOption('extra-plugins'); if (!empty($pluginsDir)) { $pluginsDir = realpath($validate->directory($pluginsDir)); } $factory = new InstallerFactory(); $factory->moodle = new Moodle($input->getOption('moodle')); $factory->plugin = new MoodlePlugin($pluginDir); $factory->execute = $this->execute; $factory->repo = $validate->gitUrl($input->getOption('repo')); $factory->branch = $validate->gitBranch($input->getOption('branch')); $factory->dataDir = $input->getOption('data'); $factory->dumper = $this->initializePluginConfigDumper($input); $factory->pluginsDir = $pluginsDir; $factory->noInit = $input->getOption('no-init'); $factory->database = $resolver->resolveDatabase( $input->getOption('db-type'), $input->getOption('db-name'), $input->getOption('db-user'), $input->getOption('db-pass'), $input->getOption('db-host') ); return $factory; }
Create a new installer factory from input options. @param InputInterface $input @return InstallerFactory
entailment
public function initializePluginConfigDumper(InputInterface $input) { $dumper = new ConfigDumper(); $dumper->addSection('filter', 'notPaths', $this->csvToArray($input->getOption('not-paths'))); $dumper->addSection('filter', 'notNames', $this->csvToArray($input->getOption('not-names'))); foreach ($this->getApplication()->all() as $command) { if (!$command instanceof AbstractPluginCommand) { continue; } $prefix = strtoupper($command->getName()); $envPaths = $prefix.'_IGNORE_PATHS'; $envNames = $prefix.'_IGNORE_NAMES'; $paths = getenv($envPaths) !== false ? getenv($envPaths) : null; $names = getenv($envNames) !== false ? getenv($envNames) : null; if (!empty($paths)) { $dumper->addSection('filter-'.$command->getName(), 'notPaths', $this->csvToArray($paths)); } if (!empty($names)) { $dumper->addSection('filter-'.$command->getName(), 'notNames', $this->csvToArray($names)); } } return $dumper; }
@param InputInterface $input @return ConfigDumper
entailment
public function csvToArray($value) { if ($value === null) { return []; } $result = explode(',', $value); $result = array_map('trim', $result); $result = array_filter($result); return array_values($result); }
Convert a CSV string to an array. Remove empties and surrounding spaces. @param string|null $value @return array
entailment
public function cacheExists($fromCurrency, $toCurrency) { return $this->storage->hasItem($this->getCacheItemName($fromCurrency, $toCurrency)); }
{@inheritDoc}
entailment
public function getRate($fromCurrency, $toCurrency) { return $this->storage->getItem($this->getCacheItemName($fromCurrency, $toCurrency)); }
{@inheritDoc}
entailment
public function createCache($fromCurrency, $toCurrency, $rate) { return $this->storage->setItem($this->getCacheItemName($fromCurrency, $toCurrency), $rate); }
{@inheritDoc}
entailment
public function addInstallers(InstallerCollection $installers) { $installers->add(new MoodleInstaller($this->execute, $this->database, $this->moodle, new MoodleConfig(), $this->repo, $this->branch, $this->dataDir)); $installers->add(new PluginInstaller($this->moodle, $this->plugin, $this->pluginsDir, $this->dumper)); $installers->add(new VendorInstaller($this->moodle, $this->plugin, $this->execute)); if ($this->noInit) { return; } if ($this->plugin->hasBehatFeatures() || $this->plugin->hasUnitTests()) { $installers->add(new TestSuiteInstaller($this->moodle, $this->plugin, $this->execute)); } }
Given a big bag of install options, add installers to the collection. @param InstallerCollection $installers Installers will be added to this
entailment
public function getVendorPaths() { $base = dirname($this->path); $paths = []; foreach ($this->xml->xpath('/libraries/library/location') as $location) { $location = trim((string) $location, '/'); $location = $base.'/'.$location; if (strpos($location, '*') !== false) { $locations = glob($location); if (empty($locations)) { throw new \RuntimeException(sprintf('Failed to run glob on path: %s', $location)); } $paths = array_merge($paths, $locations); } elseif (!file_exists($location)) { throw new \RuntimeException(sprintf('The %s contains a non-existent path: %s', $this->path, $location)); } else { $paths[] = $location; } } return $paths; }
Returns all the third party library paths from the XML file. @return array
entailment
public function getRelativeVendorPaths() { $base = dirname($this->path).'/'; return array_map(function ($path) use ($base) { return str_replace($base, '', $path); }, $this->getVendorPaths()); }
Returns all the third party library paths from the XML file. The paths will be relative to the XML file. @return array
entailment
protected function addMoodleOption(Command $command) { $moodle = getenv('MOODLE_DIR') !== false ? getenv('MOODLE_DIR') : '.'; $command->addOption('moodle', 'm', InputOption::VALUE_REQUIRED, 'Path to Moodle', $moodle); return $command; }
Adds the 'moodle' option to a command. @param Command $command @return Command
entailment
protected function initializeMoodle(InputInterface $input) { if (!$this->moodle) { $validate = new Validate(); $moodleDir = realpath($validate->directory($input->getOption('moodle'))); $this->moodle = new Moodle($moodleDir); } }
Initialize the moodle property based on input if necessary. @param InputInterface $input
entailment
private function realPath($path) { $result = realpath($path); if ($result === false) { throw new \InvalidArgumentException(sprintf('Failed to run realpath(\'%s\')', $path)); } return $result; }
@param string $path @return string
entailment
public function directory($path) { $dir = $this->realPath($path); if (!is_dir($dir)) { throw new \InvalidArgumentException(sprintf('The path is not a directory: %s', $dir)); } return $path; }
Validate a directory path. @param string $path @return string
entailment
public function filePath($path) { $file = $this->realPath($path); if (!is_file($file)) { throw new \InvalidArgumentException(sprintf('The path is not a file: %s', $file)); } return $path; }
Validate a file path. @param string $path @return string
entailment
public function gitBranch($branch) { $options = ['options' => ['regexp' => '/^[a-zA-Z0-9\/\+\._-]+$/']]; if (filter_var($branch, FILTER_VALIDATE_REGEXP, $options) === false) { throw new \InvalidArgumentException(sprintf("Invalid characters found in git branch name '%s'. Use only letters, numbers, underscore, hyphen and forward slashes.", $branch)); } return $branch; }
Validate git branch name. @param string $branch @return string
entailment
public function gitUrl($url) { // Source/credit: https://github.com/jonschlinkert/is-git-url/blob/master/index.js $options = ['options' => ['regexp' => '/(?:git|ssh|https?|git@[\w\.]+):(?:\/\/)?[\w\.@:\/~_-]+\.git(?:\/?|\#[\d\w\.\-_]+?)$/']]; if (filter_var($url, FILTER_VALIDATE_REGEXP, $options) === false) { throw new \InvalidArgumentException(sprintf('Invalid URL: %s', $url)); } return $url; }
Validate git URL. @param string $url @return string
entailment
public function restorePlugin() { (new Filesystem())->mirror($this->backupDir, $this->plugin->directory, null, ['delete' => true, 'override' => true]); }
Revert any changes Grunt tasks might have done.
entailment
public function validatePluginFiles(OutputInterface $output) { $code = 0; // Look for modified files or files that should be deleted. $files = Finder::create()->files()->in($this->backupDir)->name('*.js')->name('*.css')->getIterator(); foreach ($files as $file) { $compareFile = $this->plugin->directory.'/'.$file->getRelativePathname(); if (!file_exists($compareFile)) { $output->writeln(sprintf('<error>File no longer generated and likely should be deleted: %s</error>', $file->getRelativePathname())); $code = 1; continue; } if (sha1_file($file->getPathname()) !== sha1_file($compareFile)) { $output->writeln(sprintf('<error>File is stale and needs to be rebuilt: %s</error>', $file->getRelativePathname())); $code = 1; } } // Look for newly generated files. $files = Finder::create()->files()->in($this->plugin->directory)->name('*.js')->name('*.css')->getIterator(); foreach ($files as $file) { if (!file_exists($this->backupDir.'/'.$file->getRelativePathname())) { $output->writeln(sprintf('<error>File is newly generated and needs to be added: %s</error>', $file->getRelativePathname())); $code = 1; } } return $code; }
Verify that no plugin files were modified, need to be deleted or were added. Only checks JS and CSS files. @param OutputInterface $output @return int
entailment
public function toGruntTask($task) { $workingDirectory = $this->moodle->directory; if (is_file($this->plugin->directory.'/Gruntfile.js')) { $workingDirectory = $this->plugin->directory; } $defaultTask = new GruntTaskModel($task, $workingDirectory); switch ($task) { case 'amd': $amdDir = $this->plugin->directory.'/amd'; if (!is_dir($amdDir)) { return null; } return new GruntTaskModel($task, $amdDir, 'amd/build'); case 'shifter': case 'yui': $yuiDir = $this->plugin->directory.'/yui'; if (!is_dir($yuiDir)) { return null; } return new GruntTaskModel($task, $yuiDir.'/src', 'yui/build'); case 'gherkinlint': if ($this->moodle->getBranch() < 33 || !$this->plugin->hasBehatFeatures()) { return null; } return new GruntTaskModel($task, $this->moodle->directory); case 'stylelint:css': return $this->plugin->hasFilesWithName('*.css') ? $defaultTask : null; case 'stylelint:less': return $this->plugin->hasFilesWithName('*.less') ? $defaultTask : null; case 'stylelint:scss': return $this->plugin->hasFilesWithName('*.scss') ? $defaultTask : null; default: return $defaultTask; } }
Create a Grunt Task Model based on the task we are trying to run. @param string $task @return GruntTaskModel|null
entailment
public function getComponent() { // Simple cache. if (!empty($this->component)) { return $this->component; } $filter = new StatementFilter(); $parser = new CodeParser(); $notFound = 'The plugin must define the $plugin->component in the version.php file.'; $statements = $parser->parseFile($this->directory.'/version.php'); try { $assign = $filter->findFirstPropertyFetchAssignment($statements, 'plugin', 'component', $notFound); } catch (\Exception $e) { $assign = $filter->findFirstPropertyFetchAssignment($statements, 'module', 'component', $notFound); } if (!$assign->expr instanceof String_) { throw new \RuntimeException('The $plugin->component must be assigned to a string in the version.php file.'); } $this->component = $assign->expr->value; return $this->component; }
Get a plugin's component name. @throws \RuntimeException @return string
entailment
public function getDependencies() { // Simple cache. if (is_array($this->dependencies)) { return $this->dependencies; } $this->dependencies = []; $filter = new StatementFilter(); $parser = new CodeParser(); $statements = $parser->parseFile($this->directory.'/version.php'); try { $assign = $filter->findFirstPropertyFetchAssignment($statements, 'plugin', 'dependencies'); } catch (\Exception $e) { try { $assign = $filter->findFirstPropertyFetchAssignment($statements, 'module', 'dependencies'); } catch (\Exception $e) { return $this->dependencies; } } if (!$assign->expr instanceof Array_) { throw new \RuntimeException('The $plugin->dependencies must be assigned to an array in the version.php file.'); } $this->dependencies = $filter->arrayStringKeys($assign->expr); return $this->dependencies; }
Get a plugin's dependencies. @return array
entailment
public function hasFilesWithName($pattern) { $result = $this->getFiles(Finder::create()->name($pattern)); return count($result) !== 0; }
Determine if the plugin has any files with a given name pattern. @param string $pattern File name pattern @return bool
entailment
public function getThirdPartyLibraryPaths() { $xmlFile = $this->directory.'/thirdpartylibs.xml'; if (!is_file($xmlFile)) { return []; } $vendors = new Vendors($xmlFile); return $vendors->getRelativeVendorPaths(); }
Get paths to 3rd party libraries within the plugin. @return array
entailment
public function getIgnores() { $configFile = $this->directory.'/.moodle-plugin-ci.yml'; if (!is_file($configFile)) { return []; } $config = Yaml::parse(file_get_contents($configFile)); // Search for context (AKA command) specific filter first. if (!empty($this->context) && array_key_exists('filter-'.$this->context, $config)) { return $config['filter-'.$this->context]; } return array_key_exists('filter', $config) ? $config['filter'] : []; }
Get ignore file information. @return array
entailment
public function getFiles(Finder $finder) { $finder->files()->in($this->directory)->ignoreUnreadableDirs(); // Ignore third party libraries. foreach ($this->getThirdPartyLibraryPaths() as $libPath) { $finder->notPath($libPath); } // Extra ignores for CI. $ignores = $this->getIgnores(); if (!empty($ignores['notPaths'])) { foreach ($ignores['notPaths'] as $notPath) { $finder->notPath($notPath); } } if (!empty($ignores['notNames'])) { foreach ($ignores['notNames'] as $notName) { $finder->notName($notName); } } $files = []; foreach ($finder as $file) { /* @var \SplFileInfo $file */ $files[] = $file->getRealPath(); } return $files; }
Get a list of plugin files. @param Finder $finder The finder to use, can be pre-configured @return array Of files
entailment
public function getRelativeFiles(Finder $finder) { $files = []; foreach ($this->getFiles($finder) as $file) { $files[] = str_replace($this->directory.'/', '', $file); } return $files; }
Get a list of plugin files, with paths relative to the plugin itself. @param Finder $finder The finder to use, can be pre-configured @return array Of files
entailment
public function compare($string) { foreach ($this->tokens as $token) { if (strcasecmp($token, $string) === 0) { $this->found = true; } } }
See if the passed string matches our token(s). @param string $string
entailment
public function compareStart($string) { $lowerString = strtolower($string); foreach ($this->tokens as $token) { if (strpos($lowerString, strtolower($token)) === 0) { $this->found = true; } } }
See if the beginning of the passed string matches our token(s). @param string $string
entailment
public function convert($from, $to, $amount = 1) { $fromCurrency = $this->parseCurrencyArgument($from); $toCurrency = $this->parseCurrencyArgument($to); if ($this->isCacheable()) { if ($this->getCacheAdapter()->cacheExists($fromCurrency, $toCurrency)) { return $this->getCacheAdapter()->getRate($fromCurrency, $toCurrency) * $amount; } elseif ($this->getCacheAdapter()->cacheExists($toCurrency, $fromCurrency)) { return (1 / $this->getCacheAdapter()->getRate($toCurrency, $fromCurrency)) * $amount; } } $rate = $this->getRateProvider()->getRate($fromCurrency, $toCurrency); if ($this->isCacheable()) { $this->getCacheAdapter()->createCache($fromCurrency, $toCurrency, $rate); } return $rate * $amount; }
{@inheritDoc}
entailment
public function setCacheAdapter(Cache\Adapter\CacheAdapterInterface $cacheAdapter) { $this->setCachable(true); $this->cacheAdapter = $cacheAdapter; return $this; }
Sets cache adapter @param Cache\Adapter\CacheAdapterInterface $cacheAdapter @return self
entailment
public function getCacheAdapter() { if (!$this->cacheAdapter) { $this->setCacheAdapter(new Cache\Adapter\FileSystem()); } return $this->cacheAdapter; }
Gets cache adapter @return Cache\Adapter\CacheAdapterInterface
entailment
protected function parseCurrencyArgument($data) { if (is_string($data)) { $currency = $data; } elseif (is_array($data)) { if (isset($data['country'])) { $currency = CountryToCurrency::getCurrency($data['country']); } elseif (isset($data['currency'])) { $currency = $data['currency']; } else { throw new Exception\InvalidArgumentException('Please provide country or currency!'); } } else { throw new Exception\InvalidArgumentException('Invalid currency provided. String or array expected.'); } return $currency; }
Parses the Currency Arguments @param string|array $data @return string @throws Exception\InvalidArgumentException
entailment
private function getFileMap(PackageInterface $package, $directory) { $files = []; $root = $this->getInstallPath($package); if (!file_exists($root . '/' . $directory)) { return []; } $iterator = new RecursiveDirectoryIterator($root . '/' . $directory, RecursiveDirectoryIterator::SKIP_DOTS); /** @var SplFileInfo $file */ foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) { if ($file->isFile()) { $path = str_replace($root . '/' . $directory . '/', '', $file->getPathname()); $files[$directory . '/' . $path] = $path; } } return $files; }
Generate a file map from the passed directory. @param PackageInterface $package The package being processed. @param string $directory The name of the directory to extract. @return array
entailment
public function dump() { if (empty($this->files)) { return; } $buffer = <<<'PHP' <?php $runonce = function(array $files, $delete = false) { foreach ($files as $file) { try { include $file; } catch (\Exception $e) {} $relpath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', $file); if ($delete && !unlink($file)) { throw new \Exception( 'The file ' . $relpath . ' cannot be deleted. ' . 'Please remove the file manually and correct the file permission settings on your server.' ); } } }; PHP; if (file_exists($this->targetFile)) { if (!is_writable($this->targetFile) || !is_file($this->targetFile)) { throw new \RuntimeException( sprintf('Runonce file "%s" exists but is not writable.', $this->targetFile) ); } $current = str_replace('.php', '_'.substr(md5(mt_rand()), 0, 8).'.php', $this->targetFile); $this->filesystem->rename($this->targetFile, $current); $buffer .= "\n\$runonce(array('" . $current . "'), true);\n"; } $buffer .= "\n\$runonce(" . var_export(array_unique($this->files), true) . ");\n"; $this->filesystem->ensureDirectoryExists(dirname($this->targetFile)); if (false === file_put_contents($this->targetFile, $buffer)) { throw new \RuntimeException(sprintf('Could not write runonce file to "%s"', $this->targetFile)); } $this->files = []; }
Dumps runonce file to the target file given in the constructor. @throws \RuntimeException If the combined runonce file exists but is not writable. @return void
entailment
public function lintFile($file, OutputInterface $output) { $manager = new Manager(); $settings = new Settings(); $settings->addPaths([$file]); ob_start(); $result = $manager->run($settings); $buffer = ob_get_contents(); ob_end_clean(); if ($result->hasError()) { $output->writeln('<error>Syntax error was found in config.php after it was updated.</error>'); $output->writeln(['<error>Review the PHP Lint report for more details:</error>', '', $buffer]); } return $result->hasError() ? 1 : 0; }
Check a single file for PHP syntax errors. @param string $file Path to the file to lint @param OutputInterface $output @return int
entailment
private function runProcesses(OutputInterface $output) { $progress = new ProgressIndicator($output); $progress->start('Starting...'); // Start all of the processes. foreach ($this->processes as $process) { $process->start(); $progress->advance(); } // Wait for each to be done. foreach ($this->processes as $name => $process) { $progress->setMessage(sprintf('Waiting for moodle-plugin-ci %s...', $name)); while ($process->isRunning()) { $progress->advance(); } } $progress->finish('Done!'); }
Run the processes in parallel. @param OutputInterface $output
entailment
private function reportOnProcesses(InputInterface $input, OutputInterface $output) { $style = new SymfonyStyle($input, $output); $result = 0; foreach ($this->processes as $name => $process) { $style->newLine(); echo $process->getOutput(); if (!$process->isSuccessful()) { $result = 1; $style->error(sprintf('Command %s failed', $name)); } $errorOutput = $process->getErrorOutput(); if (!empty($errorOutput)) { $style->error(sprintf('Error output for %s command', $name)); $style->writeln($errorOutput); } } return $result; }
Report on the completed processes. @param InputInterface $input @param OutputInterface $output @return int
entailment
public function checkOutputForProblems() { if (!$this->isStarted()) { throw new \LogicException(sprintf('Process must be started before calling %s.', __FUNCTION__)); } if ($this->isOutputDisabled()) { throw new \LogicException('Output has been disabled, cannot verify if Moodle script ran without problems'); } if ($this->hasPhpErrorMessages($this->getErrorOutput())) { throw new MoodlePhpException($this); } if ($this->hasDebuggingMessages($this->getOutput())) { throw new MoodleDebugException($this); } }
Checks to make sure that there are no problems with the output. Problems would include PHP errors or Moodle debugging messages.
entailment
public function installPluginIntoMoodle(MoodlePlugin $plugin) { $this->getOutput()->info(sprintf('Installing %s', $plugin->getComponent())); $directory = $this->moodle->getComponentInstallDirectory($plugin->getComponent()); if (is_dir($directory)) { throw new \RuntimeException('Plugin is already installed in standard Moodle'); } $this->getOutput()->info(sprintf('Copying plugin from %s to %s', $plugin->directory, $directory)); // Install the plugin. $filesystem = new Filesystem(); $filesystem->mirror($plugin->directory, $directory); return $directory; }
Install the plugin into Moodle. @param MoodlePlugin $plugin @return string
entailment
public function createConfigFile($toFile) { if (file_exists($toFile)) { $this->getOutput()->debug('Config file already exists in plugin, skipping creation of config file.'); return; } if (!$this->configDumper->hasConfig()) { $this->getOutput()->debug('No config to write out, skipping creation of config file.'); return; } $this->configDumper->dump($toFile); $this->getOutput()->debug('Created config file at '.$toFile); }
Create plugin config file. @param string $toFile
entailment
protected function outputSkip(OutputInterface $output, $message = null) { $message = $message ?: 'No relevant files found to process, free pass!'; $output->writeln('<info>'.$message.'</info>'); return 0; }
@param OutputInterface $output @param string|null $message @return int
entailment
protected function behatTagsFactory(array $tags) { $fileTokens = []; $files = Finder::create()->files()->in($this->plugin->directory)->path('tests/behat')->name('*.feature')->getIterator(); foreach ($files as $file) { $fileTokens[] = FileTokens::create($file->getRelativePathname())->mustHaveAll($tags); } return $fileTokens; }
Factory method for generating FileTokens instances for all feature files in a plugin. @param array $tags @return FileTokens[]
entailment
public function addMessagesFromTokens($type, FileTokens $fileTokens) { foreach ($fileTokens->tokens as $token) { if ($token->hasTokenBeenFound()) { $this->addSuccess(sprintf('In %s, found %s %s', $fileTokens->file, $type, implode(' OR ', $token->tokens))); } else { $this->addError(sprintf('In %s, failed to find %s %s', $fileTokens->file, $type, implode(' OR ', $token->tokens))); } } }
Add messages about finding or not finding tokens in a file. @param string $type @param FileTokens $fileTokens
entailment
public function verifyRequirements() { $this->findRequiredFiles($this->requirements->getRequiredFiles()); $this->findRequiredTokens(new FunctionFinder(), $this->requirements->getRequiredFunctions()); $this->findRequiredTokens(new ClassFinder(), $this->requirements->getRequiredClasses()); $this->findRequiredTokens(new LangFinder(), [$this->requirements->getRequiredStrings()]); $this->findRequiredTokens(new CapabilityFinder(), [$this->requirements->getRequiredCapabilities()]); $this->findRequiredTokens(new TableFinder(), [$this->requirements->getRequiredTables()]); $this->findRequiredTokens(new TablePrefixFinder(), [$this->requirements->getRequiredTablePrefix()]); $this->findRequiredTokens(new BehatTagFinder(), $this->requirements->getRequiredBehatTags()); }
Run verification of a plugin.
entailment
public function findRequiredFiles(array $files) { foreach ($files as $file) { if (file_exists($this->plugin->directory.'/'.$file)) { $this->addSuccess(sprintf('Found required file: %s', $file)); } else { $this->addError(sprintf('Failed to find required file: %s', $file)); } } }
Ensure a list of files exists. @param array $files
entailment
public function findRequiredTokens(FinderInterface $finder, array $tokenCollection) { foreach ($tokenCollection as $fileTokens) { if (!$fileTokens->hasTokens()) { continue; } $file = $this->plugin->directory.'/'.$fileTokens->file; if (!file_exists($file)) { $this->addWarning(sprintf('Skipping validation of missing or optional file: %s', $fileTokens->file)); continue; } try { $finder->findTokens($file, $fileTokens); $this->addMessagesFromTokens($finder->getType(), $fileTokens); } catch (\Exception $e) { $this->addError($e->getMessage()); } } }
Find required tokens in a file. @param FinderInterface $finder @param FileTokens[] $tokenCollection
entailment
public function parse($string, Banking\Mt940\Engine $engine = null) { if (!empty($string)) { // load engine if ($engine === null) { $engine = Banking\Mt940\Engine::__getInstance($string); } $this->engine = $engine; if ($this->engine instanceof Banking\Mt940\Engine) { // parse using the engine $this->engine->loadString($string); return $this->engine->parse(); } } return []; }
Parse the given string into an array of Banking\Statement objects. @param string $string @param Banking\Mt940\Engine $engine @return \Kingsquare\Banking\Statement[]
entailment
public function getStash(?string $key = null) { $content = json_decode(file_get_contents($this->temp()), true); return $key ? (isset($content[$key]) ? $content[$key] : null) : $content; }
Retrieve the contents of the relevant file. @param string|null $key @return mixed
entailment
protected function startServer(): void { $this->guardServerStarting(); $this->process = new Process($this->prepareCommand()); $this->process->setWorkingDirectory($this->laravelPublicPath()); $this->process->start(); }
Start the server. Execute the command and open a pointer to it. Tuck away the output as it's not relevant for us during our testing. @throws \Orchestra\Testbench\Dusk\Exceptions\UnableToStartServer @return void
entailment
protected function guardServerStarting() { if ($socket = @fsockopen($this->host, $this->port, $errorNumber = 0, $errorString = '', $timeout = 1)) { fclose($socket); throw new UnableToStartServer($this->host.':'.$this->port); } }
Verify that there isn't an existing server on the host and port that we want to use. Sometimes a server can be left oped when PHP drops out, or the user may have another service running. @throws \Orchestra\Testbench\Dusk\Exceptions\UnableToStartServer
entailment
protected function prepareCommand(): string { return sprintf( (($this->isWindows() ? '' : 'exec ') .'%s -S %s:%s %s'), (new PhpExecutableFinder())->find(false), $this->host, $this->port, __DIR__.'/server.php' ); }
Prepare the command for starting the PHP server. @return string
entailment
protected function setUpTheBrowserEnvironment() { Browser::$baseUrl = $this->baseUrl(); $this->prepareDirectories(); Browser::$userResolver = function () { return $this->user(); }; }
Setup the browser environment. @return void
entailment
protected function prepareDirectories() { $tests = $this->resolveBrowserTestsPath(); foreach (['/screenshots', '/console'] as $dir) { if (! is_dir($tests.$dir)) { mkdir($tests.$dir, 0777, true); } } Browser::$storeScreenshotsAt = $tests.'/screenshots'; Browser::$storeConsoleLogAt = $tests.'/console'; }
Ensure the directories we need for dusk exist, and set them for the Browser to use. @throws \Exception @return void
entailment
public static function __getInstance($string) { $engine = self::detectBank($string); $engine->loadString($string); return $engine; }
reads the firstline of the string to guess which engine to use for parsing. @param string $string @return Engine
entailment
public static function registerEngine($engineClass, $priority) { if (!is_int($priority)) { trigger_error('Priority must be integer', E_USER_WARNING); return; } if (array_key_exists($priority, self::$registeredEngines)) { trigger_error('Priority already taken', E_USER_WARNING); return; } if (!class_exists($engineClass)) { trigger_error('Engine does not exist', E_USER_WARNING); return; } self::$registeredEngines[$priority] = $engineClass; }
Register a new Engine. @param string $engineClass Class name of Engine to be registered @param int $priority
entailment
private static function detectBank($string) { ksort(self::$registeredEngines, SORT_NUMERIC); foreach (self::$registeredEngines as $engineClass) { if ($engineClass::isApplicable($string)) { return new $engineClass(); } } trigger_error('Unknown mt940 parser loaded, thus reverted to default'); return new Engine\Unknown(); }
@param string $string @return Engine
entailment
protected function parseStatementAccount() { $results = []; if (preg_match('/:25:([\d\.]+)*/', $this->getCurrentStatementData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccount($results[1]); } // SEPA / IBAN if (preg_match('/:25:([A-Z0-9]{8}[\d\.]+)*/', $this->getCurrentStatementData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccount($results[1]); } return ''; }
uses field 25 to gather accoutnumber. @return string accountnumber
entailment
protected function parseStatementPrice($key) { $results = []; if (preg_match('/:' . $key . ':([CD])?.*[A-Z]{3}([\d,\.]+)*/', $this->getCurrentStatementData(), $results) && !empty($results[2]) ) { $sanitizedPrice = $this->sanitizePrice($results[2]); return (!empty($results[1]) && $results[1] === 'D') ? -$sanitizedPrice : $sanitizedPrice; } return ''; }
The actual pricing parser for statements. @param string $key @return float|string
entailment
protected function parseStatementNumber() { $results = []; if (preg_match('/:28C?:(.*)/', $this->getCurrentStatementData(), $results) && !empty($results[1]) ) { return trim($results[1]); } return ''; }
uses the 28C field to determine the statement number. @return string
entailment
protected function parseTransactionPrice() { $results = []; if (preg_match('/^:61:.*?[CD]([\d,\.]+)N/i', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizePrice($results[1]); } return 0; }
uses the 61 field to determine amount/value of the transaction. @return float
entailment