_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q244000
TimeWindow.getStorageKey
validation
protected function getStorageKey($key, $limit, $milliseconds) { $window = $milliseconds * (floor((microtime(1) * 1000)/$milliseconds)); $date = date('YmdHis', $window/1000); return $date . '::' . $key . '::' . $limit . '::' . $milliseconds . '::COUNT'; }
php
{ "resource": "" }
q244001
GitBranches.fetchBranches
validation
public function fetchBranches(bool $onlyRemote = false): array { $options = $onlyRemote ? ['r' => true] : ['a' => true]; $output = $this->gitWorkingCopy->branch($options); $branches = (array) preg_split("/\r\n|\n|\r/", rtrim($output)); return array_map([$this, 'trimBranch'], $branches); }
php
{ "resource": "" }
q244002
GitLoggerEventSubscriber.getLogLevelMapping
validation
public function getLogLevelMapping(string $eventName): string { if (! isset($this->logLevelMappings[$eventName])) { throw new GitException(sprintf('Unknown event "%s"', $eventName)); } return $this->logLevelMappings[$eventName]; }
php
{ "resource": "" }
q244003
GitLoggerEventSubscriber.log
validation
public function log(GitEvent $gitEvent, string $message, array $context = [], ?string $eventName = null): void { // Provide backwards compatibility with Symfony 2. if ($eventName === null && method_exists($gitEvent, 'getName')) { $eventName = $gitEvent->getName(); } $method = $this->getLogLevelMapping($eventName); $context += ['command' => $gitEvent->getProcess()->getCommandLine()]; $this->logger->{$method}($message, $context); }
php
{ "resource": "" }
q244004
GitWorkingCopy.isCloned
validation
public function isCloned(): bool { if ($this->cloned === null) { $gitDir = $this->directory; if (is_dir($gitDir . '/.git')) { $gitDir .= '/.git'; } $this->cloned = is_dir($gitDir . '/objects') && is_dir($gitDir . '/refs') && is_file($gitDir . '/HEAD'); } return $this->cloned; }
php
{ "resource": "" }
q244005
GitWorkingCopy.run
validation
public function run(string $command, array $argsAndOptions = [], bool $setDirectory = true): string { $command = new GitCommand($command, ...$argsAndOptions); if ($setDirectory) { $command->setDirectory($this->directory); } return $this->gitWrapper->run($command); }
php
{ "resource": "" }
q244006
GitWorkingCopy.isUpToDate
validation
public function isUpToDate(): bool { if (! $this->isTracking()) { throw new GitException( 'Error: HEAD does not have a remote tracking branch. Cannot check if it is up-to-date.' ); } $mergeBase = $this->run('merge-base', ['@', '@{u}']); $remoteSha = $this->run('rev-parse', ['@{u}']); return $mergeBase === $remoteSha; }
php
{ "resource": "" }
q244007
GitWorkingCopy.isAhead
validation
public function isAhead(): bool { if (! $this->isTracking()) { throw new GitException('Error: HEAD does not have a remote tracking branch. Cannot check if it is ahead.'); } $mergeBase = $this->run('merge-base', ['@', '@{u}']); $localSha = $this->run('rev-parse', ['@']); $remoteSha = $this->run('rev-parse', ['@{u}']); return $mergeBase === $remoteSha && $localSha !== $remoteSha; }
php
{ "resource": "" }
q244008
GitWorkingCopy.pushTag
validation
public function pushTag(string $tag, string $repository = 'origin', array $options = []): string { return $this->push($repository, 'tag', $tag, $options); }
php
{ "resource": "" }
q244009
GitWorkingCopy.checkoutNewBranch
validation
public function checkoutNewBranch(string $branch, array $options = []): string { $options['b'] = true; return $this->checkout($branch, $options); }
php
{ "resource": "" }
q244010
GitWorkingCopy.addRemote
validation
public function addRemote(string $name, string $url, array $options = []): string { $this->ensureAddRemoveArgsAreValid($name, $url); $args = ['add']; // Add boolean options. foreach (['-f', '--tags', '--no-tags'] as $option) { if (! empty($options[$option])) { $args[] = $option; } } // Add tracking branches. if (! empty($options['-t'])) { foreach ($options['-t'] as $branch) { array_push($args, '-t', $branch); } } // Add master branch. if (! empty($options['-m'])) { array_push($args, '-m', $options['-m']); } // Add remote name and URL. array_push($args, $name, $url); return $this->remote(...$args); }
php
{ "resource": "" }
q244011
GitWorkingCopy.getRemoteUrl
validation
public function getRemoteUrl(string $remote, string $operation = 'fetch'): string { $argsAndOptions = ['get-url', $remote]; if ($operation === 'push') { $argsAndOptions[] = '--push'; } return rtrim($this->remote(...$argsAndOptions)); }
php
{ "resource": "" }
q244012
GitWorkingCopy.cloneRepository
validation
public function cloneRepository(string $repository, array $options = []): string { $argsAndOptions = [$repository, $this->directory, $options]; return $this->run('clone', $argsAndOptions, false); }
php
{ "resource": "" }
q244013
GitWorkingCopy.init
validation
public function init(array $options = []): string { $argsAndOptions = [$this->directory, $options]; return $this->run('init', $argsAndOptions, false); }
php
{ "resource": "" }
q244014
GitTags.fetchTags
validation
public function fetchTags(): array { $output = $this->gitWorkingCopy->tag(['l' => true]); $tags = (array) preg_split("/\r\n|\n|\r/", rtrim($output)); return array_map([$this, 'trimTags'], $tags); }
php
{ "resource": "" }
q244015
GitWrapper.setPrivateKey
validation
public function setPrivateKey(string $privateKey, int $port = 22, ?string $wrapper = null): void { if ($wrapper === null) { $wrapper = __DIR__ . '/../bin/git-ssh-wrapper.sh'; } if (! $wrapperPath = realpath($wrapper)) { throw new GitException('Path to GIT_SSH wrapper script could not be resolved: ' . $wrapper); } if (! $privateKeyPath = realpath($privateKey)) { throw new GitException('Path private key could not be resolved: ' . $privateKey); } $this->setEnvVar('GIT_SSH', $wrapperPath); $this->setEnvVar('GIT_SSH_KEY', $privateKeyPath); $this->setEnvVar('GIT_SSH_PORT', $port); }
php
{ "resource": "" }
q244016
GitWrapper.streamOutput
validation
public function streamOutput(bool $streamOutput = true): void { if ($streamOutput && ! isset($this->gitOutputListener)) { $this->gitOutputListener = new GitOutputStreamListener(); $this->addOutputListener($this->gitOutputListener); } if (! $streamOutput && isset($this->gitOutputListener)) { $this->removeOutputListener($this->gitOutputListener); unset($this->gitOutputListener); } }
php
{ "resource": "" }
q244017
GitWrapper.parseRepositoryName
validation
public static function parseRepositoryName(string $repositoryUrl): string { $scheme = parse_url($repositoryUrl, PHP_URL_SCHEME); if ($scheme === null) { $parts = explode('/', $repositoryUrl); $path = end($parts); } else { $strpos = strpos($repositoryUrl, ':'); $path = substr($repositoryUrl, $strpos + 1); } /** @var string $path */ return basename($path, '.git'); }
php
{ "resource": "" }
q244018
GitWrapper.init
validation
public function init(string $directory, array $options = []): GitWorkingCopy { $git = $this->workingCopy($directory); $git->init($options); $git->setCloned(true); return $git; }
php
{ "resource": "" }
q244019
GitWrapper.cloneRepository
validation
public function cloneRepository(string $repository, ?string $directory = null, array $options = []): GitWorkingCopy { if ($directory === null) { $directory = self::parseRepositoryName($repository); } $git = $this->workingCopy($directory); $git->cloneRepository($repository, $options); $git->setCloned(true); return $git; }
php
{ "resource": "" }
q244020
GitWrapper.git
validation
public function git(string $commandLine, ?string $cwd = null): string { $command = new GitCommand($commandLine); $command->executeRaw(is_string($commandLine)); $command->setDirectory($cwd); return $this->run($command); }
php
{ "resource": "" }
q244021
GitCommand.buildOptions
validation
public function buildOptions(): array { $options = []; foreach ($this->options as $option => $values) { foreach ((array) $values as $value) { // Render the option. $prefix = strlen($option) !== 1 ? '--' : '-'; $options[] = $prefix . $option; // Render apend the value if the option isn't a flag. if ($value !== true) { $options[] = $value; } } } return $options; }
php
{ "resource": "" }
q244022
GitCommand.getCommandLine
validation
public function getCommandLine() { if ($this->executeRaw) { return $this->getCommand(); } $command = array_merge([$this->getCommand()], $this->buildOptions(), $this->args); return array_filter($command, 'strlen'); }
php
{ "resource": "" }
q244023
Text.renderShadowMark
validation
public function renderShadowMark($count, $current, $eolInterval = 60) { $this->progressCount++; $this->write('<fg=blue;options=bold>S</fg=blue;options=bold>', false); if (($this->progressCount % $eolInterval) == 0) { $counter = str_pad($this->progressCount, 5, ' ', STR_PAD_LEFT); $this->write( ' |' . $counter . ' (' . str_pad($current, strlen($count), ' ', STR_PAD_LEFT) . '/' . $count . ')' . PHP_EOL, false ); } }
php
{ "resource": "" }
q244024
Text.renderSummaryReport
validation
public function renderSummaryReport(Collector $collector) { $pkills = str_pad($collector->getKilledCount(), 8, ' ', STR_PAD_LEFT); $pescapes = str_pad($collector->getEscapeCount(), 8, ' ', STR_PAD_LEFT); $perrors = str_pad($collector->getErrorCount(), 8, ' ', STR_PAD_LEFT); $ptimeouts = str_pad($collector->getTimeoutCount(), 8, ' ', STR_PAD_LEFT); $pshadows = str_pad($collector->getShadowCount(), 8, ' ', STR_PAD_LEFT); $this->write(PHP_EOL, false); $this->write($collector->getTotalCount() . ' mutations were generated:'); $this->write($pkills . ' mutants were killed'); $this->write($pshadows . ' mutants were not covered by tests'); $this->write($pescapes . ' covered mutants were not detected'); $this->write($perrors . ' fatal errors were encountered'); $this->write($ptimeouts . ' time outs were encountered'); $this->write(PHP_EOL, false); $vanquishedTotal = $collector->getVanquishedTotal(); $measurableTotal = $collector->getMeasurableTotal(); if ($measurableTotal !== 0) { $detectionRateTested = round(100 * ($vanquishedTotal / $measurableTotal)); } else { $detectionRateTested = 0; } if ($collector->getTotalCount() !== 0) { $coveredRate = round(100 * (($measurableTotal) / $collector->getTotalCount())); $detectionRateAll = round(100 * ($vanquishedTotal / $collector->getTotalCount())); } else { $coveredRate = 0; $detectionRateAll = 0; } $this->write('Metrics:'); $this->write(' Mutation Score Indicator (MSI): <options=bold>' . $detectionRateAll . '%</options=bold>'); $this->write(' Mutation Code Coverage: <options=bold>' . $coveredRate . '%</options=bold>'); $this->write(' Covered Code MSI: <options=bold>' . $detectionRateTested . '%</options=bold>'); $this->write(PHP_EOL, false); $this->write('Remember that some mutants will inevitably be harmless (i.e. false positives).'); }
php
{ "resource": "" }
q244025
Text.indent
validation
private function indent($output, $asArray = false) { $lines = explode("\n", $output); $out = []; foreach ($lines as $line) { $out[] = ' > ' . $line; } if ($asArray) { return $out; } $return = implode("\n", $out); return $return; }
php
{ "resource": "" }
q244026
Text.extractFail
validation
private function extractFail($output) { if (preg_match('%##teamcity\[testFailed.*\]%', $output, $matches)) { preg_match( "/##teamcity\\[testFailed.*name='(.*)' message='(.*)' details='\\s*(.*)' flowId=.*/", $output, $matches ); $matches = $this->replaceEscapedChars($matches); $fail = sprintf( 'Test Name: %s' . PHP_EOL . 'Failure Message: %s' . PHP_EOL . 'Trace:' . PHP_EOL . '%s', $matches[1], $matches[2], $matches[3] ); return $fail; } return 'No failure output was detected by Humbug, but a failure was reported by PHPUnit.'; }
php
{ "resource": "" }
q244027
Addition.mutates
validation
public static function mutates(array &$tokens, $index) { $t = $tokens[$index]; if (!is_array($t) && $t == '+') { $tokenCount = count($tokens); for ($i = $index + 1; $i < $tokenCount; $i++) { // check for short array syntax if (!is_array($tokens[$i]) && $tokens[$i][0] == '[') { return false; } // check for long array syntax if (is_array($tokens[$i]) && $tokens[$i][0] == T_ARRAY && $tokens[$i][1] == 'array') { return false; } // if we're at the end of the array // and we didn't see any array, we // can probably mutate this addition if (!is_array($tokens[$i]) && $tokens[$i] == ';') { return true; } } return true; } return false; }
php
{ "resource": "" }
q244028
Humbug.execute
validation
protected function execute(InputInterface $input, OutputInterface $output) { if (PHP_SAPI !== 'phpdbg' && !defined('HHVM_VERSION') && !extension_loaded('xdebug')) { $output->writeln( '<error>You need to install and enable xdebug, or use phpdbg, ' . 'in order to allow for code coverage generation.</error>' ); return 1; } Performance::upMemProfiler(); $this->validate($input); $container = $this->container = new Container($input->getOptions()); $this->doConfiguration($input); if ($this->isLoggingEnabled()) { $this->removeOldLogFiles(); } else { $output->writeln('<error>No log file is specified. Detailed results ' . 'will not be available.</error>'); $output->write(PHP_EOL); } if ($input->getOption('incremental')) { $output->writeln('<error>Incremental Analysis is an experimental feature and will very likely</error>'); $output->writeln('<error>yield inaccurate results at this time.</error>'); $output->write(PHP_EOL); } if ($this->textLogFile) { $renderer = new Text($output, true); } else { $renderer = new Text($output); } /** * Make initial test run to ensure tests are in a starting passing state * and also log the results so test runs during the mutation phase can * be optimised. */ $testSuiteRunner = new UnitTestRunner( $container->getAdapter(), $container->getAdapter()->getProcess($container, true), $container->getTempDirectory() . '/coverage.humbug.txt' ); $testSuiteRunner->addObserver( new LoggingObserver( $renderer, $output, new ProgressBarObserver($input, $output) ) ); $result = $testSuiteRunner->run($container); /** * Check if the initial test run ended with a fatal error */ if (! $result->isSuccess()) { return 1; } $output->write(PHP_EOL); /** * Message re Static Analysis */ $renderer->renderStaticAnalysisStart(); $output->write(PHP_EOL); $incrementalCache = null; if ($input->getOption('incremental')) { $incrementalCache = new IncrementalCache($container); } $mutationTestingRunner = $this->builder->build($container, $renderer, $input, $output); $mutationTestingRunner->run($result->getCoverage(), $this->mutableIterator, $incrementalCache); if ($this->isLoggingEnabled()) { $output->write(PHP_EOL); } if ($input->getOption('incremental')) { $incrementalCache->write(); } }
php
{ "resource": "" }
q244029
IntegerValue.getMutation
validation
public static function getMutation(array &$tokens, $index) { $num = (integer) $tokens[$index][1]; if ($num == 0) { $replace = 1; } elseif ($num == 1) { $replace = 0; } else { $replace = $num + 1; } $tokens[$index] = [ T_LNUMBER, (string) $replace ]; }
php
{ "resource": "" }
q244030
Tokenizer.reconstructFromTokens
validation
public static function reconstructFromTokens(array &$tokens) { $str = ''; foreach ($tokens as $token) { if (is_string($token)) { $str .= $token; } else { $str .= $token[1]; } } return $str; }
php
{ "resource": "" }
q244031
FloatValue.getMutation
validation
public static function getMutation(array &$tokens, $index) { $num = (float) $tokens[$index][1]; if ($num == 0) { $replace = 1.0; } elseif ($num == 1) { $replace = 0.0; } elseif ($num < 2) { $replace = $num + 1; } else { $replace = 1.0; } $tokens[$index] = [ T_DNUMBER, sprintf("%.2f", $replace) ]; }
php
{ "resource": "" }
q244032
AdapterAbstract.hasOks
validation
public function hasOks($output) { $result = preg_match_all("%##teamcity\[testFinished%", $output); if ($result) { $this->okCount += $result; return $this->okCount; } return false; }
php
{ "resource": "" }
q244033
Container.get
validation
public function get($option) { if (!array_key_exists($option, $this->inputOptions)) { throw new \InvalidArgumentException('Option "'. $option . ' not exists'); } return $this->inputOptions[$option]; }
php
{ "resource": "" }
q244034
Container.getCacheDirectory
validation
public function getCacheDirectory() { if (!is_null($this->cacheDirectory)) { return $this->cacheDirectory; } if (defined('PHP_WINDOWS_VERSION_MAJOR')) { if (!getenv('APPDATA')) { throw new RuntimeException( 'The APPDATA environment variable must be set for humbug.' ); } $home = strtr(getenv('APPDATA'), '\\', '/') . '/Humbug'; } else { if (!getenv('HOME')) { throw new RuntimeException( 'The HOME environment variable must be set for humbug.' ); } $home = rtrim(getenv('HOME'), '/') . '/.humbug'; } $cache = $home . '/cache'; foreach ([$home, $cache] as $dir) { if (!is_dir($dir)) { mkdir($dir, 0777); } } file_put_contents($home . '/.htaccess', 'Deny from all'); $this->cacheDirectory = $cache; return $cache; }
php
{ "resource": "" }
q244035
Container.setTempDirectory
validation
public function setTempDirectory($dir) { $dir = rtrim($dir, ' \\/'); if (!is_dir($dir) || !is_readable($dir)) { throw new InvalidArgumentException('Invalid cache directory: "'.$dir.'"'); } $this->tempDirectory = $dir; return $this; }
php
{ "resource": "" }
q244036
Container.getTempDirectory
validation
public function getTempDirectory() { if (is_null($this->tempDirectory)) { $root = sys_get_temp_dir(); if (!is_dir($root . '/humbug')) { mkdir($root . '/humbug', 0777, true); } $this->tempDirectory = $root . '/humbug'; } return $this->tempDirectory; }
php
{ "resource": "" }
q244037
Container.setAdapterOptionsFromString
validation
public function setAdapterOptionsFromString($optionString) { $this->adapterOptions = array_merge( $this->adapterOptions, explode(' ', $optionString) ); return $this; }
php
{ "resource": "" }
q244038
Container.getAdapter
validation
public function getAdapter() { if (is_null($this->adapter)) { $name = ucfirst(strtolower($this->get('adapter'))); $class = '\\Humbug\\Adapter\\' . $name; $this->adapter = new $class; } return $this->adapter; }
php
{ "resource": "" }
q244039
Mutant.toArray
validation
public function toArray() { return [ 'file' => $this->getMutationFileRelativePath(), 'mutator' => $this->mutation->getMutator(), 'class' => $this->mutation->getClass(), 'method' => $this->mutation->getMethod(), 'line' => $this->mutation->getLine(), 'diff' => $this->getDiff(), 'tests' => $this->testMethods ]; }
php
{ "resource": "" }
q244040
Job.generate
validation
public static function generate($mutantFile = null, $bootstrap = '', $replacingFile = null) { $loadHumbug = ''; if ('phar:' === substr(__FILE__, 0, 5)) { $loadHumbug = '\Phar::loadPhar(\'' . str_replace('phar://', '', \Phar::running()) . '\', \'humbug.phar\');'; $humbugBootstrap = 'phar://humbug.phar' . '/bootstrap.php'; } else { $humbugBootstrap = realpath(__DIR__ . '/../../../bootstrap.php'); } $file = sys_get_temp_dir() . '/humbug.phpunit.bootstrap.php'; if (!is_null($mutantFile)) { $mutantFile = addslashes($mutantFile); $replacingFile = addslashes($replacingFile); $prepend = <<<PREPEND <?php {$loadHumbug} require_once '{$humbugBootstrap}'; use Humbug\StreamWrapper\IncludeInterceptor; IncludeInterceptor::intercept('{$replacingFile}', '{$mutantFile}'); IncludeInterceptor::enable(); PREPEND; if (!empty($bootstrap)) { $buffer = $prepend . "\nrequire_once '{$bootstrap}';"; } else { $buffer = $prepend; } file_put_contents($file, $buffer); } else { if (!empty($bootstrap)) { $buffer = "<?php\n{$loadHumbug}\nrequire_once '{$humbugBootstrap}';\nrequire_once '{$bootstrap}';"; } else { $buffer = "<?php\n{$loadHumbug}\nrequire_once '{$humbugBootstrap}';"; } file_put_contents($file, $buffer); } }
php
{ "resource": "" }
q244041
BeanMethod.generateBeanCreationCode
validation
protected static function generateBeanCreationCode( string $padding, string $beanId, string $methodParams, BeanPostProcessorsProperty $postProcessorsProperty ): string { $content = $padding . '$instance = parent::' . $beanId . '(' . $methodParams . ');' . PHP_EOL; $content .= $padding . 'if ($instance instanceof \\' . InitializedBean::class . ') { ' . PHP_EOL; $content .= $padding . ' $instance->postInitialization();' . PHP_EOL; $content .= $padding . '}' . PHP_EOL; $content .= PHP_EOL; $content .= $padding . 'foreach ($this->' . $postProcessorsProperty->getName() . ' as $postProcessor) { ' . PHP_EOL; $content .= $padding . ' $postProcessor->postProcess($instance, "' . $beanId . '");' . PHP_EOL; $content .= $padding . '}' . PHP_EOL; return $content; }
php
{ "resource": "" }
q244042
BeanMethod.generateNonLazyBeanCode
validation
protected static function generateNonLazyBeanCode( string $padding, string $beanId, string $beanType, Bean $beanMetadata, string $methodParams, ForceLazyInitProperty $forceLazyInitProperty, SessionBeansProperty $sessionBeansProperty, BeanPostProcessorsProperty $postProcessorsProperty, WrapBeanAsLazy $wrapBeanAsLazy ): string { $content = $padding . '$backupForceLazyInit = $this->' . $forceLazyInitProperty->getName() . ';' . PHP_EOL; if ($beanMetadata->isSession()) { $content .= $padding . 'if($this->' . $sessionBeansProperty->getName() . '->has("' . $beanId . '")) {' . PHP_EOL; if ($beanMetadata->isSingleton()) { $content .= $padding . ' $sessionInstance = clone $this->' . $sessionBeansProperty->getName() . '->get("' . $beanId . '");' . PHP_EOL; } else { $content .= $padding . ' $sessionInstance = $this->' . $sessionBeansProperty->getName() . '->get("' . $beanId . '");' . PHP_EOL; } $content .= $padding . ' return ($backupForceLazyInit) ? $this->' . $wrapBeanAsLazy->getName() . '("' . $beanId . '", "' . $beanType . '", $sessionInstance) : $sessionInstance;' . PHP_EOL; $content .= $padding . '}' . PHP_EOL; } if ($beanMetadata->isSingleton()) { $content .= $padding . 'static $instance = null;' . PHP_EOL; $content .= $padding . 'if ($instance !== null) {' . PHP_EOL; $content .= $padding . ' return ($backupForceLazyInit) ? $this->' . $wrapBeanAsLazy->getName() . '("' . $beanId . '", "' . $beanType . '", $instance) : $instance;' . PHP_EOL; $content .= $padding . '}' . PHP_EOL; } if ($beanMetadata->isSession()) { $content .= $padding . '$this->' . $forceLazyInitProperty->getName() . ' = true;' . PHP_EOL; } $content .= self::generateBeanCreationCode($padding, $beanId, $methodParams, $postProcessorsProperty); if ($beanMetadata->isSession()) { $content .= $padding . '$this->' . $forceLazyInitProperty->getName() . ' = $backupForceLazyInit;' . PHP_EOL; $content .= $padding . '$this->' . $sessionBeansProperty->getName() . '->add("' . $beanId . '", $instance);' . PHP_EOL; } $content .= $padding . 'return ($backupForceLazyInit) ? $this->' . $wrapBeanAsLazy->getName() . '("' . $beanId . '", "' . $beanType . '", $instance) : $instance;' . PHP_EOL; return $content; }
php
{ "resource": "" }
q244043
AnnotationAttributeParser.parseBooleanValue
validation
public static function parseBooleanValue($value): bool { if (\is_bool($value)) { return $value; } if (\is_string($value)) { $value = \strtolower($value); return 'true' === $value; } if (\is_object($value) || \is_array($value) || \is_callable($value)) { return false; } // anything else is simply casted to bool return (bool) $value; }
php
{ "resource": "" }
q244044
BeanFactoryConfiguration.setProxyTargetDir
validation
public function setProxyTargetDir(string $proxyTargetDir): void { if (!is_dir($proxyTargetDir)) { throw new InvalidArgumentException( sprintf( 'Proxy target directory "%s" does not exist!', $proxyTargetDir ), 10 ); } if (!is_writable($proxyTargetDir)) { throw new InvalidArgumentException( sprintf( 'Proxy target directory "%s" is not writable!', $proxyTargetDir ), 20 ); } $this->proxyTargetDir = $proxyTargetDir; }
php
{ "resource": "" }
q244045
Sheep_Debug_IndexController.searchAction
validation
public function searchAction() { /** @var Sheep_Debug_Model_Resource_RequestInfo_Collection $requests */ $requests = $this->_getFilteredRequests(); $this->loadLayout('sheep_debug'); /** @var Mage_Page_Block_Html $rootBlock */ $rootBlock = $this->getLayout()->getBlock('root'); $rootBlock->setHeaderTitle($this->__('Request profiles')); /** @var Sheep_Debug_Block_View $profileListBlock */ $profileListBlock = $this->getLayout()->getBlock('sheep_debug_list'); $profileListBlock->setData('results', $requests); $this->renderLayout(); }
php
{ "resource": "" }
q244046
Sheep_Debug_IndexController.viewAction
validation
public function viewAction() { $token = (string)$this->getRequest()->getParam('token'); if (!$token) { $this->getResponse()->setHttpResponseCode(400); return $this->_getRefererUrl(); } /** @var Sheep_Debug_Model_RequestInfo $requestInfo */ $requestInfo = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestInfo->getId()) { $this->getResponse()->setHttpResponseCode(404); return $this->_getRefererUrl(); } $section = $this->getRequest()->getParam('panel', 'request'); if (!in_array($section, array('request', 'performance', 'events', 'db', 'logging', 'email', 'layout', 'config'))) { $section = 'request'; } Mage::register('sheep_debug_request_info', $requestInfo); $blockName = 'sheep_debug_' . $section; $blockTemplate = "sheep_debug/view/panel/{$section}.phtml"; // Add section block to content area $this->loadLayout(); $layout = $this->getLayout(); $sectionBlock = $layout->createBlock('sheep_debug/view', $blockName, array('template' => $blockTemplate)); $layout->getBlock('sheep_debug_content')->insert($sectionBlock); $layout->getBlock('root')->setHeaderTitle($this->__('Profile for request %s (%s)', $requestInfo->getRequestPath(), $requestInfo->getToken())); $this->renderLayout(); }
php
{ "resource": "" }
q244047
Sheep_Debug_IndexController.viewLogAction
validation
public function viewLogAction() { $token = $this->getRequest()->getParam('token'); $log = $this->getRequest()->getParam('log'); if (!$token || !$log) { $this->getResponse()->setHttpResponseCode(400)->setBody('Invalid parameters'); return; } /** @var Sheep_Debug_Model_RequestInfo $requestProfile */ $requestProfile = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestProfile->getId()) { $this->getResponse()->setHttpResponseCode(404)->setBody('Request profile not found'); return; } try { $content = $requestProfile->getLogging()->getLoggedContent($log); $this->getResponse()->setHttpResponseCode(200)->setBody($content); } catch (Exception $e) { $this->getResponse()->setHttpResponseCode(200)->setBody('Unable to retrieve logged content'); } }
php
{ "resource": "" }
q244048
Sheep_Debug_IndexController.purgeProfilesAction
validation
public function purgeProfilesAction() { $count = $this->getService()->purgeAllProfiles(); $this->getSession()->addSuccess($this->__('%d request profiles were deleted', $count)); $this->_redirect('/'); }
php
{ "resource": "" }
q244049
Sheep_Debug_IndexController._getFilteredRequests
validation
protected function _getFilteredRequests() { /** @var Sheep_Debug_Model_Resource_RequestInfo_Collection $requests */ $requests = Mage::getModel('sheep_debug/requestInfo')->getCollection(); $requests->setCurPage(1); $requests->setPageSize(Mage::helper('sheep_debug/filter')->getLimitDefaultValue()); if ($sessionId = $this->getRequest()->getParam('session_id')) { $requests->addSessionIdFilter($sessionId); } if ($ip = $this->getRequest()->getParam('ip')) { $requests->addIpFilter($ip); } if ($method = $this->getRequest()->getParam('method')) { $requests->addHttpMethodFilter($method); } if ($limit = $this->getRequest()->getParam('limit')) { $requests->setPageSize($limit); } if ($path = $this->getRequest()->getParam('path')) { $requests->addRequestPathFilter($path); } if ($token = $this->getRequest()->getParam('token')) { $requests->addTokenFilter($token); } if ($startDate = $this->getRequest()->getParam('start')) { $requests->addAfterFilter($startDate); } if ($endDate = $this->getRequest()->getParam('end')) { $requests->addEarlierFilter($endDate); } if ($page = (int)$this->getRequest()->getParam('page')) { $requests->setCurPage($page); } $requests->addOrder('id', Varien_Data_Collection_Db::SORT_ORDER_DESC); return $requests; }
php
{ "resource": "" }
q244050
Sheep_Debug_Block_Toolbar.getVisiblePanels
validation
public function getVisiblePanels() { if ($this->visiblePanels === null) { $this->visiblePanels = array(); $panels = $this->getSortedChildBlocks(); foreach ($panels as $panel) { if (!$panel instanceof Sheep_Debug_Block_Panel) { continue; } $this->visiblePanels[] = $panel; } } return $this->visiblePanels; }
php
{ "resource": "" }
q244051
Sheep_Debug_Model_RequestInfo.initLogging
validation
public function initLogging() { $helper = Mage::helper('sheep_debug'); $this->logging = Mage::getModel('sheep_debug/logging'); $this->logging->addFile($helper->getLogFilename($this->getStoreId())); $this->logging->addFile($helper->getExceptionLogFilename($this->getStoreId())); Mage::dispatchEvent('sheep_debug_init_logging', array('logging' => $this->logging)); $this->logging->startRequest(); }
php
{ "resource": "" }
q244052
Sheep_Debug_Model_RequestInfo.getEvents
validation
public function getEvents() { if ($this->events === null) { $this->events = array(); foreach ($this->getTimers() as $timerName => $timer) { if (strpos($timerName, 'DISPATCH EVENT:') === 0) { $this->events[str_replace('DISPATCH EVENT:', '', $timerName)] = array( 'name' => str_replace('DISPATCH EVENT:', '', $timerName), 'count' => $timer['count'], 'sum' => round($timer['sum'] * 1000, 2), // ms 'mem_diff' => $timer['realmem'] / pow(1024, 2), // mb ); } } } return $this->events; }
php
{ "resource": "" }
q244053
Sheep_Debug_Model_RequestInfo.getObservers
validation
public function getObservers() { if ($this->observers === null) { $this->observers = array(); foreach ($this->getTimers() as $timerName => $timer) { if (strpos($timerName, 'OBSERVER') === 0) { $this->observers[] = array( 'name' => $timerName, 'count' => $timer['count'], 'sum' => round($timer['sum'] * 1000, 2), // ms 'mem_diff' => $timer['realmem'] / pow(1024, 2), // MB ); } } } return $this->observers; }
php
{ "resource": "" }
q244054
Sheep_Debug_Model_RequestInfo.initController
validation
public function initController($controllerAction = null) { /** @var Sheep_Debug_Model_Controller $controller */ $controller = Mage::getModel('sheep_debug/controller'); $controller->init($controllerAction); $this->action = $controller; }
php
{ "resource": "" }
q244055
Sheep_Debug_Model_RequestInfo.getBlock
validation
public function getBlock($blockName) { if (!array_key_exists($blockName, $this->blocks)) { throw new Exception('Unable to find block with name ' . $blockName); } return $this->blocks[$blockName]; }
php
{ "resource": "" }
q244056
Sheep_Debug_Model_RequestInfo.addCollection
validation
public function addCollection(Varien_Data_Collection_Db $collection) { $info = Mage::getModel('sheep_debug/collection'); $info->init($collection); $key = $info->getClass(); if (!array_key_exists($key, $this->collections)) { $this->collections[$key] = $info; } $this->collections[$key]->incrementCount(); }
php
{ "resource": "" }
q244057
Sheep_Debug_Model_RequestInfo.getCollectionsAsArray
validation
public function getCollectionsAsArray() { $data = array(); foreach ($this->getCollections() as $collection) { $data[] = array( 'type' => $collection->getType(), 'class' => $collection->getClass(), 'sql' => $collection->getQuery(), 'count' => $collection->getCount() ); } return $data; }
php
{ "resource": "" }
q244058
Sheep_Debug_Model_RequestInfo.addModel
validation
public function addModel(Mage_Core_Model_Abstract $model) { $modelInfo = Mage::getModel('sheep_debug/model'); $modelInfo->init($model); $key = $modelInfo->getClass(); if (!array_key_exists($key, $this->models)) { $this->models[$key] = $modelInfo; } $this->models[$key]->incrementCount(); }
php
{ "resource": "" }
q244059
Sheep_Debug_Model_RequestInfo.getModelsAsArray
validation
public function getModelsAsArray() { $data = array(); foreach ($this->getModels() as $model) { $data[] = array( 'resource_name' => $model->getResource(), 'class' => $model->getClass(), 'count' => $model->getCount() ); } return $data; }
php
{ "resource": "" }
q244060
Sheep_Debug_Model_RequestInfo.initQueries
validation
public function initQueries() { $this->queries = array(); $profiler = Mage::helper('sheep_debug')->getSqlProfiler(); if ($profiler->getEnabled() && $profiler instanceof Sheep_Debug_Model_Db_Profiler) { /** @var Zend_Db_Profiler_Query[] $queries */ $this->queries = $profiler->getQueryModels() ?: array(); $this->setQueryCount($profiler->getTotalNumQueries()); $this->setQueryTime($profiler->getTotalElapsedSecs()); } }
php
{ "resource": "" }
q244061
Sheep_Debug_Model_RequestInfo.getSerializedInfo
validation
public function getSerializedInfo() { return serialize(array( 'logging' => $this->getLogging(), 'action' => $this->getController(), 'design' => $this->getDesign(), 'blocks' => $this->getBlocks(), 'models' => $this->getModels(), 'collections' => $this->getCollections(), 'queries' => $this->getQueries(), 'timers' => $this->getTimers(), 'emails' => $this->getEmails() )); }
php
{ "resource": "" }
q244062
Sheep_Debug_Model_RequestInfo._beforeSave
validation
protected function _beforeSave() { parent::_beforeSave(); if (!$this->getId()) { $this->setToken($this->generateToken()); $this->setHttpMethod($this->getController()->getHttpMethod()); $this->setResponseCode($this->getController()->getResponseCode()); $this->setIp($this->getController()->getRemoteIp()); } $this->setRequestPath($this->getController()->getRequestOriginalPath()); $this->setSessionId($this->getController()->getSessionId()); $this->setInfo($this->getSerializedInfo()); return $this; }
php
{ "resource": "" }
q244063
Sheep_Debug_Model_RequestInfo._afterLoad
validation
protected function _afterLoad() { $info = $this->getUnserializedInfo(); $this->logging = $info['logging']; $this->action = $info['action']; $this->design = $info['design']; $this->blocks = $info['blocks']; $this->models = $info['models']; $this->collections = $info['collections']; $this->queries = $info['queries']; $this->timers = $info['timers']; $this->emails = $info['emails']; return parent::_afterLoad(); }
php
{ "resource": "" }
q244064
Sheep_Debug_Model_Cron.deleteExpiredRequests
validation
public function deleteExpiredRequests() { $helper = Mage::helper('sheep_debug'); if (!$helper->isEnabled()) { return 'skipped: module is disabled.'; } if ($helper->getPersistLifetime() == 0) { return 'skipped: lifetime is set to 0'; } $expirationDate = $this->getExpirationDate(date(self::DATE_FORMAT)); $table = $this->getRequestsTable(); $deleteSql = "DELETE FROM {$table} WHERE date <= '{$expirationDate}'"; /** @var Magento_Db_Adapter_Pdo_Mysql $connection */ $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); /** @var Varien_Db_Statement_Pdo_Mysql $result */ $result = $connection->query($deleteSql); return "{$result->rowCount()} requests deleted"; }
php
{ "resource": "" }
q244065
Sheep_Debug_Model_Cron.getExpirationDate
validation
public function getExpirationDate($currentDate) { $numberOfDays = Mage::helper('sheep_debug')->getPersistLifetime(); return date(self::DATE_FORMAT, strtotime("-{$numberOfDays} days {$currentDate}")); }
php
{ "resource": "" }
q244066
Sheep_Debug_Block_Abstract.__
validation
public function __() { $args = func_get_args(); return $this->helper->useStoreLocale() ? $this->parentTranslate($args) : $this->dummyTranslate($args); }
php
{ "resource": "" }
q244067
Sheep_Debug_Block_Abstract.getRequestViewUrl
validation
public function getRequestViewUrl($panel = null, $token = null) { $token = $token ?: $this->getRequestInfo()->getToken(); return $token ? Mage::helper('sheep_debug/url')->getRequestViewUrl($token, $panel) : '#'; }
php
{ "resource": "" }
q244068
Sheep_Debug_Block_Abstract.formatNumber
validation
public function formatNumber($number, $precision = 2) { return $this->helper->useStoreLocale() ? $this->helper->formatNumber($number, $precision) : number_format($number, $precision); }
php
{ "resource": "" }
q244069
Sheep_Debug_Block_Abstract.getOptionArray
validation
public function getOptionArray(array $data) { $options = array(); foreach ($data as $value) { $options[] = array('value' => $value, 'label' => $value); } return $options; }
php
{ "resource": "" }
q244070
Sheep_Debug_ModelController.enableSqlProfilerAction
validation
public function enableSqlProfilerAction() { try { $this->getService()->setSqlProfilerStatus(true); $this->getService()->flushCache(); Mage::getSingleton('core/session')->addSuccess('SQL profiler was enabled.'); } catch (Exception $e) { Mage::getSingleton('core/session')->addError('Unable to enable SQL profiler: ' . $e->getMessage()); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244071
Sheep_Debug_ModelController.disableSqlProfilerAction
validation
public function disableSqlProfilerAction() { try { $this->getService()->setSqlProfilerStatus(false); $this->getService()->flushCache(); Mage::getSingleton('core/session')->addSuccess('SQL profiler was disabled.'); } catch (Exception $e) { Mage::getSingleton('core/session')->addError('Unable to disable SQL profiler: ' . $e->getMessage()); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244072
Sheep_Debug_ModelController.selectSqlAction
validation
public function selectSqlAction() { if ($query = $this->_initQuery()) { $helper = Mage::helper('sheep_debug'); $results = $helper->runSql($query->getQuery(), $query->getQueryParams()); $this->renderTable($results); } }
php
{ "resource": "" }
q244073
Sheep_Debug_ModelController.stacktraceSqlAction
validation
public function stacktraceSqlAction() { if ($query = $this->_initQuery()) { $helper = Mage::helper('sheep_debug'); $stripZendPath = $helper->canStripZendDbTrace() ? 'lib/Zend/Db/Adapter' : ''; $trimPath = $helper->canTrimMagentoBaseDir() ? Mage::getBaseDir() . DS : ''; $html = '<pre>' . Mage::helper('sheep_debug')->formatStacktrace($query->getStackTrace(), $stripZendPath, $trimPath) . '</pre>'; $this->getResponse()->setBody($html); } }
php
{ "resource": "" }
q244074
Sheep_Debug_ModelController._initQuery
validation
protected function _initQuery() { $token = $this->getRequest()->getParam('token'); $index = $this->getRequest()->getParam('index'); if ($token === null || $index === null) { $this->getResponse()->setHttpResponseCode(400)->setBody('Invalid parameters'); return null; } /** @var Sheep_Debug_Model_RequestInfo $requestProfile */ $requestProfile = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestProfile->getId()) { $this->getResponse()->setHttpResponseCode(404)->setBody('Request profile not found'); return null; } $queries = $requestProfile->getQueries(); if (!$queries || !($index < count($queries))) { $this->getResponse()->setHttpResponseCode(404)->setBody('Query not found'); return null; } /** @var Zend_Db_Profiler_Query $query */ return $queries[(int)$index]; }
php
{ "resource": "" }
q244075
Sheep_Debug_Model_Block.startRendering
validation
public function startRendering(Mage_Core_Block_Abstract $block) { if ($this->isRendering) { // Recursive block instances with same name is used - we don't update render start time $this->renderedCount++; Mage::log("Recursive block rendering {$this->getName()}", Zend_Log::DEBUG); return; } // Re-init data from block (some extension might update dynamically block's template) $this->init($block); $this->isRendering = true; $this->renderedCount++; $this->renderedAt = microtime(true); if (self::$startRenderingTime===null) { self::$startRenderingTime = $this->renderedAt; } }
php
{ "resource": "" }
q244076
Sheep_Debug_Model_Block.completeRendering
validation
public function completeRendering(Mage_Core_Block_Abstract $block) { $this->isRendering = false; $this->renderedCompletedAt = microtime(true); $this->renderedDuration += ($this->renderedCompletedAt * 1000 - $this->renderedAt * 1000); $this->templateFile = $block instanceof Mage_Core_Block_Template ? $block->getTemplateFile() : ''; self::$endRenderingTime = $this->renderedCompletedAt; }
php
{ "resource": "" }
q244077
Sheep_Debug_Model_Design.getLayoutUpdates
validation
public function getLayoutUpdates() { if ($this->uncompressedLayoutUpdates === null) { $this->uncompressedLayoutUpdates = $this->layoutUpdates ? json_decode(gzuncompress($this->layoutUpdates), true) : array(); } return $this->uncompressedLayoutUpdates; }
php
{ "resource": "" }
q244078
Sheep_Debug_Model_Design.getInfoAsArray
validation
public function getInfoAsArray() { return array( 'design_area' => $this->getArea(), 'package_name' => $this->getPackageName(), 'layout_theme' => $this->getThemeLayout(), 'template_theme' => $this->getThemeTemplate(), 'locale' => $this->getThemeLocale(), 'skin' => $this->getThemeSkin() ); }
php
{ "resource": "" }
q244079
Sheep_Debug_Block_View.getRequestInfo
validation
public function getRequestInfo() { if ($this->requestInfo === null) { $this->requestInfo = Mage::registry('sheep_debug_request_info'); } return $this->requestInfo; }
php
{ "resource": "" }
q244080
Sheep_Debug_Block_View.getFilteredRequestListUrl
validation
public function getFilteredRequestListUrl($filters = array()) { // Preserver current filter $currentFilters = Mage::helper('sheep_debug/filter')->getRequestFilters($this->getRequest()); $filters = array_merge($currentFilters, $filters); return $this->getRequestListUrl($filters); }
php
{ "resource": "" }
q244081
Sheep_Debug_Block_View.renderArrayAsText
validation
public function renderArrayAsText($array) { $values = array(); foreach ($array as $key => $value) { $values[] = $this->escapeHtml($key) . ' = ' . $this->renderValue($value); } return implode(', ', $values); }
php
{ "resource": "" }
q244082
Sheep_Debug_Block_View.renderArray
validation
public function renderArray($data, $noDataLabel = 'No Data', $header = null) { /** @var Mage_Core_Block_Template $block */ $block = $this->getLayout()->createBlock('sheep_debug/view'); $block->setTemplate('sheep_debug/view/panel/_array.phtml'); $block->setData('array', $data); $block->setData('no_data_label', $noDataLabel); $block->setData('header', $header); return $block->toHtml(); }
php
{ "resource": "" }
q244083
Sheep_Debug_Block_View.getBlocksAsTree
validation
public function getBlocksAsTree() { $blocks = $this->getRequestInfo()->getBlocks(); $tree = new Varien_Data_Tree(); $rootNodes = array(); foreach ($blocks as $block) { $parentNode = $tree->getNodeById($block->getParentName()); $node = new Varien_Data_Tree_Node(array( 'name' => $block->getName(), 'class' => $block->getClass(), 'template' => $block->getTemplateFile(), 'duration' => $block->getRenderedDuration(), 'count' => $block->getRenderedCount() ), 'name', $tree, $parentNode); $tree->addNode($node, $parentNode); if (!$parentNode) { $rootNodes[] = $node; } } return $rootNodes; }
php
{ "resource": "" }
q244084
Sheep_Debug_Block_View.getBlockTreeHtml
validation
public function getBlockTreeHtml() { $content = ''; $rootNodes = $this->getBlocksAsTree(); // Try to iterate our non-conventional tree foreach ($rootNodes as $rootNode) { $content .= $this->renderTreeNode($rootNode); } return $content; }
php
{ "resource": "" }
q244085
Sheep_Debug_Block_View.renderTreeNode
validation
public function renderTreeNode(Varien_Data_Tree_Node $node, $indentLevel=0) { $block = $this->getLayout()->createBlock('sheep_debug/view'); $block->setRequestInfo($this->getRequestInfo()); $block->setTemplate('sheep_debug/view/panel/_block_node.phtml'); $block->setNode($node); $block->setIndent($indentLevel); return $block->toHtml(); }
php
{ "resource": "" }
q244086
Sheep_Debug_Helper_Http.getRequestPath
validation
public function getRequestPath() { $requestPath = ''; $server = $this->getGlobalServer(); if (array_key_exists('REQUEST_URI', $server)) { $requestPath = parse_url($server['REQUEST_URI'], PHP_URL_PATH); } return $requestPath; }
php
{ "resource": "" }
q244087
Sheep_Debug_Helper_Url.getUrl
validation
public function getUrl($path, array $params = array()) { $path = self::MODULE_ROUTE . $path; $params['_store'] = $this->getRouteStoreId(); $params['_nosid'] = true; return $this->_getUrl($path, $params); }
php
{ "resource": "" }
q244088
Sheep_Debug_Model_Service.getModuleConfigFilePath
validation
public function getModuleConfigFilePath($moduleName) { $config = $this->getConfig(); $moduleConfig = $config->getModuleConfig($moduleName); if (!$moduleConfig) { throw new Exception("Unable to find module '{$moduleName}'"); } return $config->getOptions()->getEtcDir() . DS . 'modules' . DS . $moduleName . '.xml'; }
php
{ "resource": "" }
q244089
Sheep_Debug_Model_Service.setModuleStatus
validation
public function setModuleStatus($moduleName, $isActive) { $moduleConfigFile = $this->getModuleConfigFilePath($moduleName); $configXml = $this->loadXmlFile($moduleConfigFile); if ($configXml === false) { throw new Exception("Unable to parse module configuration file {$moduleConfigFile}"); } $configXml->modules->{$moduleName}->active = $isActive ? 'true' : 'false'; // save if ($this->saveXml($configXml, $moduleConfigFile) === false) { throw new Exception("Unable to save module configuration file {$moduleConfigFile}. Check to see if web server user has write permissions."); } }
php
{ "resource": "" }
q244090
Sheep_Debug_Model_Service.setSqlProfilerStatus
validation
public function setSqlProfilerStatus($isEnabled) { $filePath = $this->getLocalXmlFilePath(); $xml = $this->loadXmlFile($filePath); if ($xml === false) { throw new Exception("Unable to parse local.xml configuration file: {$filePath}"); } /** @var SimpleXMLElement $connectionNode */ $connectionNode = $xml->global->resources->default_setup->connection; if ($isEnabled) { /** @noinspection PhpUndefinedFieldInspection */ $connectionNode->profiler = '1'; } else { unset($connectionNode->profiler); } if ($this->saveXml($xml, $filePath) === false) { throw new Exception("Unable to save {$filePath}: check if web server user has write permission"); } }
php
{ "resource": "" }
q244091
Sheep_Debug_Model_Service.setTemplateHints
validation
public function setTemplateHints($status) { $this->deleteTemplateHintsDbConfigs(); $config = $this->getConfig(); $config->saveConfig('dev/debug/template_hints', (int)$status); $config->saveConfig('dev/debug/template_hints_blocks', (int)$status); }
php
{ "resource": "" }
q244092
Sheep_Debug_Model_Service.searchConfig
validation
public function searchConfig($query) { $configArray = array(); $configArray = Mage::helper('sheep_debug')->xml2array($this->getConfig()->getNode(), $configArray); $results = array(); $configKeys = array_keys($configArray); foreach ($configKeys as $configKey) { if (strpos($configKey, $query) !== FALSE) { $results[$configKey] = $configArray[$configKey]; } } return $results; }
php
{ "resource": "" }
q244093
Sheep_Debug_Model_Service.deleteTemplateHintsDbConfigs
validation
public function deleteTemplateHintsDbConfigs() { $configTable = Mage::getResourceModel('core/config')->getMainTable(); /** @var Magento_Db_Adapter_Pdo_Mysql $db */ $db = Mage::getSingleton('core/resource')->getConnection('core_write'); $db->delete($configTable, "path like 'dev/debug/template_hints%'"); }
php
{ "resource": "" }
q244094
Sheep_Debug_Model_Service.purgeAllProfiles
validation
public function purgeAllProfiles() { $table = Mage::getResourceModel('sheep_debug/requestInfo')->getMainTable(); $deleteSql = "DELETE FROM {$table}"; /** @var Magento_Db_Adapter_Pdo_Mysql $connection */ $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); /** @var Varien_Db_Statement_Pdo_Mysql $result */ $result = $connection->query($deleteSql); return $result->rowCount(); }
php
{ "resource": "" }
q244095
Sheep_Debug_Model_Service.getFileUpdatesWithHandle
validation
public function getFileUpdatesWithHandle($handle, $storeId, $area) { /** @var array $updateFiles */ $updateFiles = Mage::helper('sheep_debug')->getLayoutUpdatesFiles($storeId, $area); /* @var $designPackage Mage_Core_Model_Design_Package */ $designPackage = Mage::getModel('core/design_package'); $designPackage->setStore($storeId); $designPackage->setArea($area); $designPackageName = $designPackage->getPackageName(); $layoutTheme = $designPackage->getTheme('layout'); // search handle in all layout files registered for this area, package name and theme $handleFiles = array(); foreach ($updateFiles as $file) { $filename = $designPackage->getLayoutFilename($file, array( '_area' => $area, '_package' => $designPackageName, '_theme' => $layoutTheme )); if (!is_readable($filename)) { continue; } /** @var SimpleXMLElement $fileXml */ $fileXml = $this->loadXmlFile($filename); if ($fileXml === false) { continue; } $relativeFilename = str_replace($this->getBaseDir(), '', $filename); /** @var SimpleXMLElement[] $result */ $results = $fileXml->xpath("/layout/{$handle}"); if ($results) { $handleFiles[$relativeFilename] = array(); /** @var SimpleXMLElement $result */ foreach ($results as $result) { $handleFiles[$relativeFilename][] = $result->asXML(); } } } return $handleFiles; }
php
{ "resource": "" }
q244096
Sheep_Debug_Model_Service.getDatabaseUpdatesWithHandle
validation
public function getDatabaseUpdatesWithHandle($handle, $storeId, $area) { $databaseHandles = array(); /* @var $designPackage Mage_Core_Model_Design_Package */ $designPackage = Mage::getModel('core/design_package'); $designPackage->setStore($storeId); $designPackage->setArea($area); /* @var $layoutResourceModel Mage_Core_Model_Resource_Layout */ $layoutResourceModel = Mage::getResourceModel('core/layout'); $bind = array( 'store_id' => $storeId, 'area' => $area, 'package' => $designPackage->getPackageName(), 'theme' => $designPackage->getTheme('layout'), 'layout_update_handle' => $handle ); /* @var $readAdapter Varien_Db_Adapter_Pdo_Mysql */ $readAdapter = Mage::getSingleton('core/resource')->getConnection('core_read'); /* @var $select Varien_Db_Select */ $select = $readAdapter->select() ->from(array('layout_update' => $layoutResourceModel->getMainTable()), array('layout_update_id', 'xml')) ->join(array('link' => $layoutResourceModel->getTable('core/layout_link')), 'link.layout_update_id=layout_update.layout_update_id', '') ->where('link.store_id IN (0, :store_id)') ->where('link.area = :area') ->where('link.package = :package') ->where('link.theme = :theme') ->where('layout_update.handle = :layout_update_handle') ->order('layout_update.sort_order ' . Varien_Db_Select::SQL_ASC); $result = $readAdapter->fetchAssoc($select, $bind); if (count($result)) { foreach ($result as $dbLayoutUpdate) { $databaseHandles[$dbLayoutUpdate['layout_update_id']] = $dbLayoutUpdate['xml']; } } return $databaseHandles; }
php
{ "resource": "" }
q244097
Sheep_Debug_Model_Collection.init
validation
public function init(Varien_Data_Collection_Db $collection) { $this->class = get_class($collection); $this->type = $collection instanceof Mage_Eav_Model_Entity_Collection_Abstract ? self::TYPE_EAV : self::TYPE_FLAT; $this->query = $collection->getSelectSql(true); $this->count = 0; }
php
{ "resource": "" }
q244098
Sheep_Debug_DesignController.viewHandleAction
validation
public function viewHandleAction() { $area = $this->getRequest()->getParam('area'); $storeId = (int)$this->getRequest()->getParam('store'); $handle = $this->getRequest()->getParam('handle'); $updatesByFile = $this->getService()->getFileUpdatesWithHandle($handle, $storeId, $area); $databaseUpdates = $this->getService()->getDatabaseUpdatesWithHandle($handle, $storeId, $area); $block = $this->getLayout()->createBlock('sheep_debug/view', '', array( 'template' => 'sheep_debug/view/panel/_layout_updates.phtml', 'file_updates' => $updatesByFile, 'db_updates' => $databaseUpdates )); $this->getResponse()->setBody($block->toHtml()); }
php
{ "resource": "" }
q244099
Sheep_Debug_DesignController.layoutUpdatesAction
validation
public function layoutUpdatesAction() { $token = $this->getRequest()->getParam('token'); if (!$token) { return $this->getResponse()->setHttpResponseCode(400)->setBody('Invalid parameters'); } /** @var Sheep_Debug_Model_RequestInfo $requestProfile */ $requestProfile = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestProfile->getId()) { return $this->getResponse()->setHttpResponseCode(404)->setBody('Request profile not found'); } $layoutUpdates = $requestProfile->getDesign()->getLayoutUpdates(); $this->renderArray($layoutUpdates, 'No Data', array('#', 'XML')); }
php
{ "resource": "" }