repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
phpbench/phpbench
lib/Serializer/XmlDecoder.php
XmlDecoder.decodeFiles
public function decodeFiles(array $files) { // combine into one document. // $suiteDocument = new Document('phpbench'); $rootEl = $suiteDocument->createRoot('phpbench'); foreach ($files as $file) { $fileDom = new Document(); $fileDom->load($file); foreach ($fileDom->query('./suite') as $suiteEl) { $importedEl = $suiteDocument->importNode($suiteEl, true); $rootEl->appendChild($importedEl); } } return $this->decode($suiteDocument); }
php
public function decodeFiles(array $files) { // combine into one document. // $suiteDocument = new Document('phpbench'); $rootEl = $suiteDocument->createRoot('phpbench'); foreach ($files as $file) { $fileDom = new Document(); $fileDom->load($file); foreach ($fileDom->query('./suite') as $suiteEl) { $importedEl = $suiteDocument->importNode($suiteEl, true); $rootEl->appendChild($importedEl); } } return $this->decode($suiteDocument); }
[ "public", "function", "decodeFiles", "(", "array", "$", "files", ")", "{", "// combine into one document.", "//", "$", "suiteDocument", "=", "new", "Document", "(", "'phpbench'", ")", ";", "$", "rootEl", "=", "$", "suiteDocument", "->", "createRoot", "(", "'phpbench'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "fileDom", "=", "new", "Document", "(", ")", ";", "$", "fileDom", "->", "load", "(", "$", "file", ")", ";", "foreach", "(", "$", "fileDom", "->", "query", "(", "'./suite'", ")", "as", "$", "suiteEl", ")", "{", "$", "importedEl", "=", "$", "suiteDocument", "->", "importNode", "(", "$", "suiteEl", ",", "true", ")", ";", "$", "rootEl", "->", "appendChild", "(", "$", "importedEl", ")", ";", "}", "}", "return", "$", "this", "->", "decode", "(", "$", "suiteDocument", ")", ";", "}" ]
Return a SuiteCollection from a number of PHPBench xml files. @param string[] $files @return SuiteCollection
[ "Return", "a", "SuiteCollection", "from", "a", "number", "of", "PHPBench", "xml", "files", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Serializer/XmlDecoder.php#L61-L79
train
phpbench/phpbench
lib/Math/Kde.php
Kde.evaluate
public function evaluate(array $points) { $count = count($this->dataset); $bigger = count($points) > $count; if ($bigger) { $range = $count - 1; } else { $range = count($points) - 1; } $result = array_fill(0, count($points), 0); // loop over points foreach (range(0, $range) as $i) { if ($bigger) { $dataValue = $this->dataset[$i]; $diff = array_map(function ($point) use ($dataValue) { return $dataValue - $point; }, $points); } else { $diff = array_map(function ($v) use ($points, $i) { return $v - $points[$i]; }, $this->dataset); } // dot product (consider dedicated function) $invCov = $this->invCov; $tDiff = array_map(function ($v) use ($invCov) { return $invCov * $v; }, $diff); // multiply the two arrays $multiplied = []; foreach ($diff as $index => $value) { $multiplied[$index] = $diff[$index] * $tDiff[$index]; } // numpy sum does nothing with our 2d array in PHP // $energy = array_sum(diff * tdiff, axis=0) / 2.0 $energy = array_map(function ($v) { return exp(-($v / 2)); }, $multiplied); if ($bigger) { $sum = $result; foreach ($sum as $index => $value) { $sum[$index] = $sum[$index] + $energy[$index]; } $result = $sum; } else { $result[$i] = array_sum($energy); } } $result = array_map(function ($v) { return $v / $this->normFactor; }, $result); return $result; }
php
public function evaluate(array $points) { $count = count($this->dataset); $bigger = count($points) > $count; if ($bigger) { $range = $count - 1; } else { $range = count($points) - 1; } $result = array_fill(0, count($points), 0); // loop over points foreach (range(0, $range) as $i) { if ($bigger) { $dataValue = $this->dataset[$i]; $diff = array_map(function ($point) use ($dataValue) { return $dataValue - $point; }, $points); } else { $diff = array_map(function ($v) use ($points, $i) { return $v - $points[$i]; }, $this->dataset); } // dot product (consider dedicated function) $invCov = $this->invCov; $tDiff = array_map(function ($v) use ($invCov) { return $invCov * $v; }, $diff); // multiply the two arrays $multiplied = []; foreach ($diff as $index => $value) { $multiplied[$index] = $diff[$index] * $tDiff[$index]; } // numpy sum does nothing with our 2d array in PHP // $energy = array_sum(diff * tdiff, axis=0) / 2.0 $energy = array_map(function ($v) { return exp(-($v / 2)); }, $multiplied); if ($bigger) { $sum = $result; foreach ($sum as $index => $value) { $sum[$index] = $sum[$index] + $energy[$index]; } $result = $sum; } else { $result[$i] = array_sum($energy); } } $result = array_map(function ($v) { return $v / $this->normFactor; }, $result); return $result; }
[ "public", "function", "evaluate", "(", "array", "$", "points", ")", "{", "$", "count", "=", "count", "(", "$", "this", "->", "dataset", ")", ";", "$", "bigger", "=", "count", "(", "$", "points", ")", ">", "$", "count", ";", "if", "(", "$", "bigger", ")", "{", "$", "range", "=", "$", "count", "-", "1", ";", "}", "else", "{", "$", "range", "=", "count", "(", "$", "points", ")", "-", "1", ";", "}", "$", "result", "=", "array_fill", "(", "0", ",", "count", "(", "$", "points", ")", ",", "0", ")", ";", "// loop over points", "foreach", "(", "range", "(", "0", ",", "$", "range", ")", "as", "$", "i", ")", "{", "if", "(", "$", "bigger", ")", "{", "$", "dataValue", "=", "$", "this", "->", "dataset", "[", "$", "i", "]", ";", "$", "diff", "=", "array_map", "(", "function", "(", "$", "point", ")", "use", "(", "$", "dataValue", ")", "{", "return", "$", "dataValue", "-", "$", "point", ";", "}", ",", "$", "points", ")", ";", "}", "else", "{", "$", "diff", "=", "array_map", "(", "function", "(", "$", "v", ")", "use", "(", "$", "points", ",", "$", "i", ")", "{", "return", "$", "v", "-", "$", "points", "[", "$", "i", "]", ";", "}", ",", "$", "this", "->", "dataset", ")", ";", "}", "// dot product (consider dedicated function)", "$", "invCov", "=", "$", "this", "->", "invCov", ";", "$", "tDiff", "=", "array_map", "(", "function", "(", "$", "v", ")", "use", "(", "$", "invCov", ")", "{", "return", "$", "invCov", "*", "$", "v", ";", "}", ",", "$", "diff", ")", ";", "// multiply the two arrays", "$", "multiplied", "=", "[", "]", ";", "foreach", "(", "$", "diff", "as", "$", "index", "=>", "$", "value", ")", "{", "$", "multiplied", "[", "$", "index", "]", "=", "$", "diff", "[", "$", "index", "]", "*", "$", "tDiff", "[", "$", "index", "]", ";", "}", "// numpy sum does nothing with our 2d array in PHP", "// $energy = array_sum(diff * tdiff, axis=0) / 2.0", "$", "energy", "=", "array_map", "(", "function", "(", "$", "v", ")", "{", "return", "exp", "(", "-", "(", "$", "v", "/", "2", ")", ")", ";", "}", ",", "$", "multiplied", ")", ";", "if", "(", "$", "bigger", ")", "{", "$", "sum", "=", "$", "result", ";", "foreach", "(", "$", "sum", "as", "$", "index", "=>", "$", "value", ")", "{", "$", "sum", "[", "$", "index", "]", "=", "$", "sum", "[", "$", "index", "]", "+", "$", "energy", "[", "$", "index", "]", ";", "}", "$", "result", "=", "$", "sum", ";", "}", "else", "{", "$", "result", "[", "$", "i", "]", "=", "array_sum", "(", "$", "energy", ")", ";", "}", "}", "$", "result", "=", "array_map", "(", "function", "(", "$", "v", ")", "{", "return", "$", "v", "/", "$", "this", "->", "normFactor", ";", "}", ",", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Evaluate the estimated pdf on a set of points. @param array $points 1-D array of points on to which we will map the kde @return array
[ "Evaluate", "the", "estimated", "pdf", "on", "a", "set", "of", "points", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Kde.php#L131-L194
train
phpbench/phpbench
lib/Math/Kde.php
Kde.setBandwidth
public function setBandwidth($bwMethod = null) { if ($bwMethod == 'scott' || null === $bwMethod) { $this->coVarianceFactor = function () { return pow(count($this->dataset), -1. / (5)); }; } elseif ($bwMethod == 'silverman') { $this->coVarianceFactor = function () { return pow(count($this->dataset) * (3.0) / 4.0, -1. / (5)); }; } elseif (is_numeric($bwMethod)) { $this->coVarianceFactor = function () use ($bwMethod) { return $bwMethod; }; } else { throw new \InvalidArgumentException(sprintf( 'Unknown bandwidth method "%s"', $bwMethod )); } $this->computeCovariance(); }
php
public function setBandwidth($bwMethod = null) { if ($bwMethod == 'scott' || null === $bwMethod) { $this->coVarianceFactor = function () { return pow(count($this->dataset), -1. / (5)); }; } elseif ($bwMethod == 'silverman') { $this->coVarianceFactor = function () { return pow(count($this->dataset) * (3.0) / 4.0, -1. / (5)); }; } elseif (is_numeric($bwMethod)) { $this->coVarianceFactor = function () use ($bwMethod) { return $bwMethod; }; } else { throw new \InvalidArgumentException(sprintf( 'Unknown bandwidth method "%s"', $bwMethod )); } $this->computeCovariance(); }
[ "public", "function", "setBandwidth", "(", "$", "bwMethod", "=", "null", ")", "{", "if", "(", "$", "bwMethod", "==", "'scott'", "||", "null", "===", "$", "bwMethod", ")", "{", "$", "this", "->", "coVarianceFactor", "=", "function", "(", ")", "{", "return", "pow", "(", "count", "(", "$", "this", "->", "dataset", ")", ",", "-", "1.", "/", "(", "5", ")", ")", ";", "}", ";", "}", "elseif", "(", "$", "bwMethod", "==", "'silverman'", ")", "{", "$", "this", "->", "coVarianceFactor", "=", "function", "(", ")", "{", "return", "pow", "(", "count", "(", "$", "this", "->", "dataset", ")", "*", "(", "3.0", ")", "/", "4.0", ",", "-", "1.", "/", "(", "5", ")", ")", ";", "}", ";", "}", "elseif", "(", "is_numeric", "(", "$", "bwMethod", ")", ")", "{", "$", "this", "->", "coVarianceFactor", "=", "function", "(", ")", "use", "(", "$", "bwMethod", ")", "{", "return", "$", "bwMethod", ";", "}", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unknown bandwidth method \"%s\"'", ",", "$", "bwMethod", ")", ")", ";", "}", "$", "this", "->", "computeCovariance", "(", ")", ";", "}" ]
Compute the estimator bandwidth with given method. The new bandwidth calculated after a call to `setBandwidth` is used for subsequent evaluations of the estimated density. @param string $bwMethod Either "scott" or "silverman"
[ "Compute", "the", "estimator", "bandwidth", "with", "given", "method", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Kde.php#L204-L226
train
phpbench/phpbench
extensions/dbal/lib/Storage/Driver/Dbal/Visitor/SqlVisitor.php
SqlVisitor.visit
public function visit(Constraint $constraint) { $sql = $this->doVisit($constraint); $return = [$sql, $this->values]; $this->values = []; $this->paramCounter = 0; $select = [ 'run.id', 'run.uuid', 'run.tag', 'run.date', 'subject.benchmark', 'subject.name', 'subject.id', 'variant.id', 'variant.sleep', 'variant.output_time_unit', 'variant.output_time_precision', 'variant.output_mode', 'variant.revolutions', 'variant.retry_threshold', 'variant.warmup', 'iteration.time', 'iteration.memory', 'iteration.reject_count', ]; $extraJoins = []; $fieldNames = $this->getFieldNames($constraint); if (in_array('group', $fieldNames)) { $extraJoins[] = 'LEFT JOIN sgroup_subject ON sgroup_subject.subject_id = subject.id'; $select[] = 'sgroup_subject.sgroup'; } if (in_array('param', $fieldNames)) { $extraJoins[] = 'LEFT JOIN variant_parameter ON variant_parameter.variant_id = variant.id'; $extraJoins[] = 'LEFT JOIN parameter ON variant_parameter.parameter_id = parameter.id'; $select[] = 'parameter.pkey'; $select[] = 'parameter.value'; } $selectSql = <<<'EOT' SELECT %s FROM iteration LEFT JOIN variant ON iteration.variant_id = variant.id LEFT JOIN subject ON variant.subject_id = subject.id LEFT JOIN run ON variant.run_id = run.id %s WHERE EOT; $select = array_map(function ($value) { return sprintf('%s AS "%s"', $value, $value); }, $select); $selectSql = sprintf( $selectSql, implode(', ', $select), implode(' ', $extraJoins) ); $return[0] = $selectSql . $return[0]; return $return; }
php
public function visit(Constraint $constraint) { $sql = $this->doVisit($constraint); $return = [$sql, $this->values]; $this->values = []; $this->paramCounter = 0; $select = [ 'run.id', 'run.uuid', 'run.tag', 'run.date', 'subject.benchmark', 'subject.name', 'subject.id', 'variant.id', 'variant.sleep', 'variant.output_time_unit', 'variant.output_time_precision', 'variant.output_mode', 'variant.revolutions', 'variant.retry_threshold', 'variant.warmup', 'iteration.time', 'iteration.memory', 'iteration.reject_count', ]; $extraJoins = []; $fieldNames = $this->getFieldNames($constraint); if (in_array('group', $fieldNames)) { $extraJoins[] = 'LEFT JOIN sgroup_subject ON sgroup_subject.subject_id = subject.id'; $select[] = 'sgroup_subject.sgroup'; } if (in_array('param', $fieldNames)) { $extraJoins[] = 'LEFT JOIN variant_parameter ON variant_parameter.variant_id = variant.id'; $extraJoins[] = 'LEFT JOIN parameter ON variant_parameter.parameter_id = parameter.id'; $select[] = 'parameter.pkey'; $select[] = 'parameter.value'; } $selectSql = <<<'EOT' SELECT %s FROM iteration LEFT JOIN variant ON iteration.variant_id = variant.id LEFT JOIN subject ON variant.subject_id = subject.id LEFT JOIN run ON variant.run_id = run.id %s WHERE EOT; $select = array_map(function ($value) { return sprintf('%s AS "%s"', $value, $value); }, $select); $selectSql = sprintf( $selectSql, implode(', ', $select), implode(' ', $extraJoins) ); $return[0] = $selectSql . $return[0]; return $return; }
[ "public", "function", "visit", "(", "Constraint", "$", "constraint", ")", "{", "$", "sql", "=", "$", "this", "->", "doVisit", "(", "$", "constraint", ")", ";", "$", "return", "=", "[", "$", "sql", ",", "$", "this", "->", "values", "]", ";", "$", "this", "->", "values", "=", "[", "]", ";", "$", "this", "->", "paramCounter", "=", "0", ";", "$", "select", "=", "[", "'run.id'", ",", "'run.uuid'", ",", "'run.tag'", ",", "'run.date'", ",", "'subject.benchmark'", ",", "'subject.name'", ",", "'subject.id'", ",", "'variant.id'", ",", "'variant.sleep'", ",", "'variant.output_time_unit'", ",", "'variant.output_time_precision'", ",", "'variant.output_mode'", ",", "'variant.revolutions'", ",", "'variant.retry_threshold'", ",", "'variant.warmup'", ",", "'iteration.time'", ",", "'iteration.memory'", ",", "'iteration.reject_count'", ",", "]", ";", "$", "extraJoins", "=", "[", "]", ";", "$", "fieldNames", "=", "$", "this", "->", "getFieldNames", "(", "$", "constraint", ")", ";", "if", "(", "in_array", "(", "'group'", ",", "$", "fieldNames", ")", ")", "{", "$", "extraJoins", "[", "]", "=", "'LEFT JOIN sgroup_subject ON sgroup_subject.subject_id = subject.id'", ";", "$", "select", "[", "]", "=", "'sgroup_subject.sgroup'", ";", "}", "if", "(", "in_array", "(", "'param'", ",", "$", "fieldNames", ")", ")", "{", "$", "extraJoins", "[", "]", "=", "'LEFT JOIN variant_parameter ON variant_parameter.variant_id = variant.id'", ";", "$", "extraJoins", "[", "]", "=", "'LEFT JOIN parameter ON variant_parameter.parameter_id = parameter.id'", ";", "$", "select", "[", "]", "=", "'parameter.pkey'", ";", "$", "select", "[", "]", "=", "'parameter.value'", ";", "}", "$", "selectSql", "=", " <<<'EOT'\nSELECT \n %s\n FROM iteration\n LEFT JOIN variant ON iteration.variant_id = variant.id\n LEFT JOIN subject ON variant.subject_id = subject.id\n LEFT JOIN run ON variant.run_id = run.id\n %s\nWHERE\n\nEOT", ";", "$", "select", "=", "array_map", "(", "function", "(", "$", "value", ")", "{", "return", "sprintf", "(", "'%s AS \"%s\"'", ",", "$", "value", ",", "$", "value", ")", ";", "}", ",", "$", "select", ")", ";", "$", "selectSql", "=", "sprintf", "(", "$", "selectSql", ",", "implode", "(", "', '", ",", "$", "select", ")", ",", "implode", "(", "' '", ",", "$", "extraJoins", ")", ")", ";", "$", "return", "[", "0", "]", "=", "$", "selectSql", ".", "$", "return", "[", "0", "]", ";", "return", "$", "return", ";", "}" ]
Convert the given constraint into an SQL query. @param Constraint $constraint @return string
[ "Convert", "the", "given", "constraint", "into", "an", "SQL", "query", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/extensions/dbal/lib/Storage/Driver/Dbal/Visitor/SqlVisitor.php#L76-L143
train
phpbench/phpbench
lib/Benchmark/BenchmarkFinder.php
BenchmarkFinder.findBenchmarks
public function findBenchmarks($path, array $subjectFilter = [], array $groupFilter = []) { $finder = new Finder(); $path = PhpBench::normalizePath($path); if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf( 'File or directory "%s" does not exist (cwd: %s)', $path, getcwd() )); } if (is_dir($path)) { $finder->in($path) ->name('*.php'); } else { // the path is already a file, just restrict the finder to that. $finder->in(dirname($path)) ->depth(0) ->name(basename($path)); } $benchmarks = []; foreach ($finder as $file) { if (!is_file($file)) { continue; } $benchmark = $this->factory->getMetadataForFile($file->getPathname()); if (null === $benchmark) { continue; } if ($groupFilter) { $benchmark->filterSubjectGroups($groupFilter); } if ($subjectFilter) { $benchmark->filterSubjectNames($subjectFilter); } if (false === $benchmark->hasSubjects()) { continue; } $benchmarks[] = $benchmark; } return $benchmarks; }
php
public function findBenchmarks($path, array $subjectFilter = [], array $groupFilter = []) { $finder = new Finder(); $path = PhpBench::normalizePath($path); if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf( 'File or directory "%s" does not exist (cwd: %s)', $path, getcwd() )); } if (is_dir($path)) { $finder->in($path) ->name('*.php'); } else { // the path is already a file, just restrict the finder to that. $finder->in(dirname($path)) ->depth(0) ->name(basename($path)); } $benchmarks = []; foreach ($finder as $file) { if (!is_file($file)) { continue; } $benchmark = $this->factory->getMetadataForFile($file->getPathname()); if (null === $benchmark) { continue; } if ($groupFilter) { $benchmark->filterSubjectGroups($groupFilter); } if ($subjectFilter) { $benchmark->filterSubjectNames($subjectFilter); } if (false === $benchmark->hasSubjects()) { continue; } $benchmarks[] = $benchmark; } return $benchmarks; }
[ "public", "function", "findBenchmarks", "(", "$", "path", ",", "array", "$", "subjectFilter", "=", "[", "]", ",", "array", "$", "groupFilter", "=", "[", "]", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "$", "path", "=", "PhpBench", "::", "normalizePath", "(", "$", "path", ")", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'File or directory \"%s\" does not exist (cwd: %s)'", ",", "$", "path", ",", "getcwd", "(", ")", ")", ")", ";", "}", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "$", "finder", "->", "in", "(", "$", "path", ")", "->", "name", "(", "'*.php'", ")", ";", "}", "else", "{", "// the path is already a file, just restrict the finder to that.", "$", "finder", "->", "in", "(", "dirname", "(", "$", "path", ")", ")", "->", "depth", "(", "0", ")", "->", "name", "(", "basename", "(", "$", "path", ")", ")", ";", "}", "$", "benchmarks", "=", "[", "]", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "if", "(", "!", "is_file", "(", "$", "file", ")", ")", "{", "continue", ";", "}", "$", "benchmark", "=", "$", "this", "->", "factory", "->", "getMetadataForFile", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "if", "(", "null", "===", "$", "benchmark", ")", "{", "continue", ";", "}", "if", "(", "$", "groupFilter", ")", "{", "$", "benchmark", "->", "filterSubjectGroups", "(", "$", "groupFilter", ")", ";", "}", "if", "(", "$", "subjectFilter", ")", "{", "$", "benchmark", "->", "filterSubjectNames", "(", "$", "subjectFilter", ")", ";", "}", "if", "(", "false", "===", "$", "benchmark", "->", "hasSubjects", "(", ")", ")", "{", "continue", ";", "}", "$", "benchmarks", "[", "]", "=", "$", "benchmark", ";", "}", "return", "$", "benchmarks", ";", "}" ]
Build the BenchmarkMetadata collection. @param string $path @param array $subjectFilter @param array $groupFilter
[ "Build", "the", "BenchmarkMetadata", "collection", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/BenchmarkFinder.php#L43-L95
train
phpbench/phpbench
lib/Report/ReportManager.php
ReportManager.generateReports
public function generateReports(SuiteCollection $collection, array $reportNames) { $reportDoms = []; $reportConfigs = []; foreach ($reportNames as $reportName) { $reportConfigs[$reportName] = $this->generatorRegistry->getConfig($reportName); } foreach ($reportConfigs as $reportName => $reportConfig) { $generatorName = $reportConfig['generator']; $generator = $this->generatorRegistry->getService($generatorName); $reportDom = $generator->generate($collection, $reportConfig); if (!$reportDom instanceof Document) { throw new \RuntimeException(sprintf( 'Report generator "%s" should have return a PhpBench\Dom\Document class, got: "%s"', $generatorName, is_object($reportDom) ? get_class($reportDom) : gettype($reportDom) )); } $reportDom->schemaValidate(__DIR__ . '/schema/report.xsd'); $reportDoms[] = $reportDom; } return $reportDoms; }
php
public function generateReports(SuiteCollection $collection, array $reportNames) { $reportDoms = []; $reportConfigs = []; foreach ($reportNames as $reportName) { $reportConfigs[$reportName] = $this->generatorRegistry->getConfig($reportName); } foreach ($reportConfigs as $reportName => $reportConfig) { $generatorName = $reportConfig['generator']; $generator = $this->generatorRegistry->getService($generatorName); $reportDom = $generator->generate($collection, $reportConfig); if (!$reportDom instanceof Document) { throw new \RuntimeException(sprintf( 'Report generator "%s" should have return a PhpBench\Dom\Document class, got: "%s"', $generatorName, is_object($reportDom) ? get_class($reportDom) : gettype($reportDom) )); } $reportDom->schemaValidate(__DIR__ . '/schema/report.xsd'); $reportDoms[] = $reportDom; } return $reportDoms; }
[ "public", "function", "generateReports", "(", "SuiteCollection", "$", "collection", ",", "array", "$", "reportNames", ")", "{", "$", "reportDoms", "=", "[", "]", ";", "$", "reportConfigs", "=", "[", "]", ";", "foreach", "(", "$", "reportNames", "as", "$", "reportName", ")", "{", "$", "reportConfigs", "[", "$", "reportName", "]", "=", "$", "this", "->", "generatorRegistry", "->", "getConfig", "(", "$", "reportName", ")", ";", "}", "foreach", "(", "$", "reportConfigs", "as", "$", "reportName", "=>", "$", "reportConfig", ")", "{", "$", "generatorName", "=", "$", "reportConfig", "[", "'generator'", "]", ";", "$", "generator", "=", "$", "this", "->", "generatorRegistry", "->", "getService", "(", "$", "generatorName", ")", ";", "$", "reportDom", "=", "$", "generator", "->", "generate", "(", "$", "collection", ",", "$", "reportConfig", ")", ";", "if", "(", "!", "$", "reportDom", "instanceof", "Document", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Report generator \"%s\" should have return a PhpBench\\Dom\\Document class, got: \"%s\"'", ",", "$", "generatorName", ",", "is_object", "(", "$", "reportDom", ")", "?", "get_class", "(", "$", "reportDom", ")", ":", "gettype", "(", "$", "reportDom", ")", ")", ")", ";", "}", "$", "reportDom", "->", "schemaValidate", "(", "__DIR__", ".", "'/schema/report.xsd'", ")", ";", "$", "reportDoms", "[", "]", "=", "$", "reportDom", ";", "}", "return", "$", "reportDoms", ";", "}" ]
Generate the named reports. @param SuiteCollection $collection @param array $reportNames @return array
[ "Generate", "the", "named", "reports", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/ReportManager.php#L52-L81
train
phpbench/phpbench
lib/Model/ResultCollection.php
ResultCollection.getMetric
public function getMetric($class, $metric) { $metrics = $this->getResult($class)->getMetrics(); if (!isset($metrics[$metric])) { throw new \InvalidArgumentException(sprintf( 'Unknown metric "%s" for result class "%s". Available metrics: "%s"', $metric, $class, implode('", "', array_keys($metrics)) )); } return $metrics[$metric]; }
php
public function getMetric($class, $metric) { $metrics = $this->getResult($class)->getMetrics(); if (!isset($metrics[$metric])) { throw new \InvalidArgumentException(sprintf( 'Unknown metric "%s" for result class "%s". Available metrics: "%s"', $metric, $class, implode('", "', array_keys($metrics)) )); } return $metrics[$metric]; }
[ "public", "function", "getMetric", "(", "$", "class", ",", "$", "metric", ")", "{", "$", "metrics", "=", "$", "this", "->", "getResult", "(", "$", "class", ")", "->", "getMetrics", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "metrics", "[", "$", "metric", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unknown metric \"%s\" for result class \"%s\". Available metrics: \"%s\"'", ",", "$", "metric", ",", "$", "class", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "metrics", ")", ")", ")", ")", ";", "}", "return", "$", "metrics", "[", "$", "metric", "]", ";", "}" ]
Return the named metric for the given result class. @param string $class @param string $metric @throws \InvalidArgumentException @return mixed
[ "Return", "the", "named", "metric", "for", "the", "given", "result", "class", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/ResultCollection.php#L89-L101
train
phpbench/phpbench
lib/Model/SuiteCollection.php
SuiteCollection.mergeCollection
public function mergeCollection(self $collection) { foreach ($collection->getSuites() as $suite) { $this->addSuite($suite); } }
php
public function mergeCollection(self $collection) { foreach ($collection->getSuites() as $suite) { $this->addSuite($suite); } }
[ "public", "function", "mergeCollection", "(", "self", "$", "collection", ")", "{", "foreach", "(", "$", "collection", "->", "getSuites", "(", ")", "as", "$", "suite", ")", "{", "$", "this", "->", "addSuite", "(", "$", "suite", ")", ";", "}", "}" ]
Merge another collection into this one. @param SuiteCollection $collection
[ "Merge", "another", "collection", "into", "this", "one", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/SuiteCollection.php#L55-L60
train
phpbench/phpbench
lib/Benchmark/Remote/Reflector.php
Reflector.getParameterSets
public function getParameterSets($file, $paramProviders) { $parameterSets = $this->launcher->payload(__DIR__ . '/template/parameter_set_extractor.template', [ 'file' => $file, 'class' => $this->getClassNameFromFile($file), 'paramProviders' => var_export($paramProviders, true), ])->launch(); // validate parameters $parameters = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($parameterSets)); iterator_apply($parameters, function (\Iterator $iterator) { $parameter = $iterator->current(); if (!is_scalar($parameter) && isset($parameter)) { throw new \InvalidArgumentException(sprintf( 'Parameter values must be scalar. Got "%s"', is_object($parameter) ? get_class($parameter) : gettype($parameter) )); } }, [$parameters]); return $parameterSets; }
php
public function getParameterSets($file, $paramProviders) { $parameterSets = $this->launcher->payload(__DIR__ . '/template/parameter_set_extractor.template', [ 'file' => $file, 'class' => $this->getClassNameFromFile($file), 'paramProviders' => var_export($paramProviders, true), ])->launch(); // validate parameters $parameters = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($parameterSets)); iterator_apply($parameters, function (\Iterator $iterator) { $parameter = $iterator->current(); if (!is_scalar($parameter) && isset($parameter)) { throw new \InvalidArgumentException(sprintf( 'Parameter values must be scalar. Got "%s"', is_object($parameter) ? get_class($parameter) : gettype($parameter) )); } }, [$parameters]); return $parameterSets; }
[ "public", "function", "getParameterSets", "(", "$", "file", ",", "$", "paramProviders", ")", "{", "$", "parameterSets", "=", "$", "this", "->", "launcher", "->", "payload", "(", "__DIR__", ".", "'/template/parameter_set_extractor.template'", ",", "[", "'file'", "=>", "$", "file", ",", "'class'", "=>", "$", "this", "->", "getClassNameFromFile", "(", "$", "file", ")", ",", "'paramProviders'", "=>", "var_export", "(", "$", "paramProviders", ",", "true", ")", ",", "]", ")", "->", "launch", "(", ")", ";", "// validate parameters", "$", "parameters", "=", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveArrayIterator", "(", "$", "parameterSets", ")", ")", ";", "iterator_apply", "(", "$", "parameters", ",", "function", "(", "\\", "Iterator", "$", "iterator", ")", "{", "$", "parameter", "=", "$", "iterator", "->", "current", "(", ")", ";", "if", "(", "!", "is_scalar", "(", "$", "parameter", ")", "&&", "isset", "(", "$", "parameter", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Parameter values must be scalar. Got \"%s\"'", ",", "is_object", "(", "$", "parameter", ")", "?", "get_class", "(", "$", "parameter", ")", ":", "gettype", "(", "$", "parameter", ")", ")", ")", ";", "}", "}", ",", "[", "$", "parameters", "]", ")", ";", "return", "$", "parameterSets", ";", "}" ]
Return the parameter sets for the benchmark container in the given file. @param string $file @param string[] $paramProviders @return array
[ "Return", "the", "parameter", "sets", "for", "the", "benchmark", "container", "in", "the", "given", "file", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Remote/Reflector.php#L90-L112
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.toDestUnit
public function toDestUnit(float $time, string $destUnit = null, string $mode = null) { return self::convert($time, $this->sourceUnit, $this->getDestUnit($destUnit), $this->getMode($mode)); }
php
public function toDestUnit(float $time, string $destUnit = null, string $mode = null) { return self::convert($time, $this->sourceUnit, $this->getDestUnit($destUnit), $this->getMode($mode)); }
[ "public", "function", "toDestUnit", "(", "float", "$", "time", ",", "string", "$", "destUnit", "=", "null", ",", "string", "$", "mode", "=", "null", ")", "{", "return", "self", "::", "convert", "(", "$", "time", ",", "$", "this", "->", "sourceUnit", ",", "$", "this", "->", "getDestUnit", "(", "$", "destUnit", ")", ",", "$", "this", "->", "getMode", "(", "$", "mode", ")", ")", ";", "}" ]
Convert instance value to given unit.
[ "Convert", "instance", "value", "to", "given", "unit", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L100-L103
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.overrideDestUnit
public function overrideDestUnit($destUnit) { self::validateUnit($destUnit); $this->destUnit = $destUnit; $this->overriddenDestUnit = true; }
php
public function overrideDestUnit($destUnit) { self::validateUnit($destUnit); $this->destUnit = $destUnit; $this->overriddenDestUnit = true; }
[ "public", "function", "overrideDestUnit", "(", "$", "destUnit", ")", "{", "self", "::", "validateUnit", "(", "$", "destUnit", ")", ";", "$", "this", "->", "destUnit", "=", "$", "destUnit", ";", "$", "this", "->", "overriddenDestUnit", "=", "true", ";", "}" ]
Override the destination unit. @param string $destUnit
[ "Override", "the", "destination", "unit", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L110-L115
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.overrideMode
public function overrideMode($mode) { self::validateMode($mode); $this->mode = $mode; $this->overriddenMode = true; }
php
public function overrideMode($mode) { self::validateMode($mode); $this->mode = $mode; $this->overriddenMode = true; }
[ "public", "function", "overrideMode", "(", "$", "mode", ")", "{", "self", "::", "validateMode", "(", "$", "mode", ")", ";", "$", "this", "->", "mode", "=", "$", "mode", ";", "$", "this", "->", "overriddenMode", "=", "true", ";", "}" ]
Override the mode. @param string $mode
[ "Override", "the", "mode", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L122-L127
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.getDestSuffix
public function getDestSuffix(string $unit = null, string $mode = null) { return self::getSuffix($this->getDestUnit($unit), $this->getMode($mode)); }
php
public function getDestSuffix(string $unit = null, string $mode = null) { return self::getSuffix($this->getDestUnit($unit), $this->getMode($mode)); }
[ "public", "function", "getDestSuffix", "(", "string", "$", "unit", "=", "null", ",", "string", "$", "mode", "=", "null", ")", "{", "return", "self", "::", "getSuffix", "(", "$", "this", "->", "getDestUnit", "(", "$", "unit", ")", ",", "$", "this", "->", "getMode", "(", "$", "mode", ")", ")", ";", "}" ]
Return the destination unit suffix.
[ "Return", "the", "destination", "unit", "suffix", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L223-L226
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.format
public function format(float $time, string $unit = null, string $mode = null, int $precision = null, bool $suffix = true) { $value = number_format($this->toDestUnit($time, $unit, $mode), $precision !== null ? $precision : $this->precision); if (false === $suffix) { return $value; } $suffix = $this->getDestSuffix($unit, $mode); return $value . $suffix; }
php
public function format(float $time, string $unit = null, string $mode = null, int $precision = null, bool $suffix = true) { $value = number_format($this->toDestUnit($time, $unit, $mode), $precision !== null ? $precision : $this->precision); if (false === $suffix) { return $value; } $suffix = $this->getDestSuffix($unit, $mode); return $value . $suffix; }
[ "public", "function", "format", "(", "float", "$", "time", ",", "string", "$", "unit", "=", "null", ",", "string", "$", "mode", "=", "null", ",", "int", "$", "precision", "=", "null", ",", "bool", "$", "suffix", "=", "true", ")", "{", "$", "value", "=", "number_format", "(", "$", "this", "->", "toDestUnit", "(", "$", "time", ",", "$", "unit", ",", "$", "mode", ")", ",", "$", "precision", "!==", "null", "?", "$", "precision", ":", "$", "this", "->", "precision", ")", ";", "if", "(", "false", "===", "$", "suffix", ")", "{", "return", "$", "value", ";", "}", "$", "suffix", "=", "$", "this", "->", "getDestSuffix", "(", "$", "unit", ",", "$", "mode", ")", ";", "return", "$", "value", ".", "$", "suffix", ";", "}" ]
Return a human readable representation of the unit including the suffix.
[ "Return", "a", "human", "readable", "representation", "of", "the", "unit", "including", "the", "suffix", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L231-L242
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.convert
public static function convert(float $time, string $unit, string $destUnit, string $mode) { self::validateMode($mode); if ($mode === self::MODE_TIME) { return self::convertTo($time, $unit, $destUnit); } return self::convertInto($time, $unit, $destUnit); }
php
public static function convert(float $time, string $unit, string $destUnit, string $mode) { self::validateMode($mode); if ($mode === self::MODE_TIME) { return self::convertTo($time, $unit, $destUnit); } return self::convertInto($time, $unit, $destUnit); }
[ "public", "static", "function", "convert", "(", "float", "$", "time", ",", "string", "$", "unit", ",", "string", "$", "destUnit", ",", "string", "$", "mode", ")", "{", "self", "::", "validateMode", "(", "$", "mode", ")", ";", "if", "(", "$", "mode", "===", "self", "::", "MODE_TIME", ")", "{", "return", "self", "::", "convertTo", "(", "$", "time", ",", "$", "unit", ",", "$", "destUnit", ")", ";", "}", "return", "self", "::", "convertInto", "(", "$", "time", ",", "$", "unit", ",", "$", "destUnit", ")", ";", "}" ]
Convert given time in given unit to given destination unit in given mode.
[ "Convert", "given", "time", "in", "given", "unit", "to", "given", "destination", "unit", "in", "given", "mode", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L247-L256
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.convertInto
public static function convertInto(float $time, string $unit, string $destUnit) { if (!$time) { return 0; } self::validateUnit($unit); self::validateUnit($destUnit); $destMultiplier = self::$map[$destUnit]; $sourceMultiplier = self::$map[$unit]; $time = $destMultiplier / ($time * $sourceMultiplier); return $time; }
php
public static function convertInto(float $time, string $unit, string $destUnit) { if (!$time) { return 0; } self::validateUnit($unit); self::validateUnit($destUnit); $destMultiplier = self::$map[$destUnit]; $sourceMultiplier = self::$map[$unit]; $time = $destMultiplier / ($time * $sourceMultiplier); return $time; }
[ "public", "static", "function", "convertInto", "(", "float", "$", "time", ",", "string", "$", "unit", ",", "string", "$", "destUnit", ")", "{", "if", "(", "!", "$", "time", ")", "{", "return", "0", ";", "}", "self", "::", "validateUnit", "(", "$", "unit", ")", ";", "self", "::", "validateUnit", "(", "$", "destUnit", ")", ";", "$", "destMultiplier", "=", "self", "::", "$", "map", "[", "$", "destUnit", "]", ";", "$", "sourceMultiplier", "=", "self", "::", "$", "map", "[", "$", "unit", "]", ";", "$", "time", "=", "$", "destMultiplier", "/", "(", "$", "time", "*", "$", "sourceMultiplier", ")", ";", "return", "$", "time", ";", "}" ]
Convert a given time INTO the given unit. That is, how many times the given time will fit into the the destination unit. i.e. `x` per unit.
[ "Convert", "a", "given", "time", "INTO", "the", "given", "unit", ".", "That", "is", "how", "many", "times", "the", "given", "time", "will", "fit", "into", "the", "the", "destination", "unit", ".", "i", ".", "e", ".", "x", "per", "unit", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L262-L277
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.convertTo
public static function convertTo(float $time, string $unit, string $destUnit) { self::validateUnit($unit); self::validateUnit($destUnit); $destM = self::$map[$destUnit]; $sourceM = self::$map[$unit]; $time = ($time * $sourceM) / $destM; return $time; }
php
public static function convertTo(float $time, string $unit, string $destUnit) { self::validateUnit($unit); self::validateUnit($destUnit); $destM = self::$map[$destUnit]; $sourceM = self::$map[$unit]; $time = ($time * $sourceM) / $destM; return $time; }
[ "public", "static", "function", "convertTo", "(", "float", "$", "time", ",", "string", "$", "unit", ",", "string", "$", "destUnit", ")", "{", "self", "::", "validateUnit", "(", "$", "unit", ")", ";", "self", "::", "validateUnit", "(", "$", "destUnit", ")", ";", "$", "destM", "=", "self", "::", "$", "map", "[", "$", "destUnit", "]", ";", "$", "sourceM", "=", "self", "::", "$", "map", "[", "$", "unit", "]", ";", "$", "time", "=", "(", "$", "time", "*", "$", "sourceM", ")", "/", "$", "destM", ";", "return", "$", "time", ";", "}" ]
Convert the given time from the given unit to the given destination unit.
[ "Convert", "the", "given", "time", "from", "the", "given", "unit", "to", "the", "given", "destination", "unit", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L283-L294
train
phpbench/phpbench
lib/Util/TimeUnit.php
TimeUnit.getSuffix
public static function getSuffix($unit, $mode = null) { self::validateUnit($unit); $suffix = self::$suffixes[$unit]; if ($mode === self::MODE_THROUGHPUT) { return sprintf('ops/%s', $suffix); } return $suffix; }
php
public static function getSuffix($unit, $mode = null) { self::validateUnit($unit); $suffix = self::$suffixes[$unit]; if ($mode === self::MODE_THROUGHPUT) { return sprintf('ops/%s', $suffix); } return $suffix; }
[ "public", "static", "function", "getSuffix", "(", "$", "unit", ",", "$", "mode", "=", "null", ")", "{", "self", "::", "validateUnit", "(", "$", "unit", ")", ";", "$", "suffix", "=", "self", "::", "$", "suffixes", "[", "$", "unit", "]", ";", "if", "(", "$", "mode", "===", "self", "::", "MODE_THROUGHPUT", ")", "{", "return", "sprintf", "(", "'ops/%s'", ",", "$", "suffix", ")", ";", "}", "return", "$", "suffix", ";", "}" ]
Return the suffix for a given unit. @static @param string $unit @param string $mode @return string
[ "Return", "the", "suffix", "for", "a", "given", "unit", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Util/TimeUnit.php#L306-L317
train
phpbench/phpbench
lib/Formatter/Formatter.php
Formatter.classesFromFile
public function classesFromFile($filename) { $classes = $this->loader->load($filename); $this->registerClasses($classes); }
php
public function classesFromFile($filename) { $classes = $this->loader->load($filename); $this->registerClasses($classes); }
[ "public", "function", "classesFromFile", "(", "$", "filename", ")", "{", "$", "classes", "=", "$", "this", "->", "loader", "->", "load", "(", "$", "filename", ")", ";", "$", "this", "->", "registerClasses", "(", "$", "classes", ")", ";", "}" ]
Register classes from a given JSON encoded class definition file. @param string $filename
[ "Register", "classes", "from", "a", "given", "JSON", "encoded", "class", "definition", "file", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Formatter/Formatter.php#L35-L39
train
phpbench/phpbench
lib/Formatter/Formatter.php
Formatter.registerClasses
public function registerClasses(array $classDefinitions) { foreach ($classDefinitions as $className => $formatDefinitions) { $this->registerClass($className, $formatDefinitions); } }
php
public function registerClasses(array $classDefinitions) { foreach ($classDefinitions as $className => $formatDefinitions) { $this->registerClass($className, $formatDefinitions); } }
[ "public", "function", "registerClasses", "(", "array", "$", "classDefinitions", ")", "{", "foreach", "(", "$", "classDefinitions", "as", "$", "className", "=>", "$", "formatDefinitions", ")", "{", "$", "this", "->", "registerClass", "(", "$", "className", ",", "$", "formatDefinitions", ")", ";", "}", "}" ]
Register class definitions. Class definitions have the form $className => (array) $formatDefinitions @param array $classDefinitions
[ "Register", "class", "definitions", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Formatter/Formatter.php#L48-L53
train
phpbench/phpbench
lib/Benchmark/Remote/ReflectionHierarchy.php
ReflectionHierarchy.hasMethod
public function hasMethod($name) { foreach ($this->reflectionClasses as $reflectionClass) { if (isset($reflectionClass->methods[$name])) { return true; } } return false; }
php
public function hasMethod($name) { foreach ($this->reflectionClasses as $reflectionClass) { if (isset($reflectionClass->methods[$name])) { return true; } } return false; }
[ "public", "function", "hasMethod", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "reflectionClasses", "as", "$", "reflectionClass", ")", "{", "if", "(", "isset", "(", "$", "reflectionClass", "->", "methods", "[", "$", "name", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Return true if the class hierarchy contains the named method. @param string $name @return bool
[ "Return", "true", "if", "the", "class", "hierarchy", "contains", "the", "named", "method", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Remote/ReflectionHierarchy.php#L68-L77
train
phpbench/phpbench
lib/Benchmark/Remote/ReflectionHierarchy.php
ReflectionHierarchy.hasStaticMethod
public function hasStaticMethod($name) { foreach ($this->reflectionClasses as $reflectionClass) { if (isset($reflectionClass->methods[$name])) { $method = $reflectionClass->methods[$name]; if ($method->isStatic) { return true; } break; } } return false; }
php
public function hasStaticMethod($name) { foreach ($this->reflectionClasses as $reflectionClass) { if (isset($reflectionClass->methods[$name])) { $method = $reflectionClass->methods[$name]; if ($method->isStatic) { return true; } break; } } return false; }
[ "public", "function", "hasStaticMethod", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "reflectionClasses", "as", "$", "reflectionClass", ")", "{", "if", "(", "isset", "(", "$", "reflectionClass", "->", "methods", "[", "$", "name", "]", ")", ")", "{", "$", "method", "=", "$", "reflectionClass", "->", "methods", "[", "$", "name", "]", ";", "if", "(", "$", "method", "->", "isStatic", ")", "{", "return", "true", ";", "}", "break", ";", "}", "}", "return", "false", ";", "}" ]
Return true if the class hierarchy contains the named static method. @param string $name @return bool
[ "Return", "true", "if", "the", "class", "hierarchy", "contains", "the", "named", "static", "method", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Remote/ReflectionHierarchy.php#L86-L101
train
phpbench/phpbench
lib/Report/Generator/Table/Row.php
Row.offsetGet
public function offsetGet($offset) { if (!$this->offsetExists($offset)) { throw new \InvalidArgumentException(sprintf( 'Column "%s" does not exist, valid columns: "%s"', $offset, implode('", "', array_keys($this->getArrayCopy())) )); } return parent::offsetGet($offset); }
php
public function offsetGet($offset) { if (!$this->offsetExists($offset)) { throw new \InvalidArgumentException(sprintf( 'Column "%s" does not exist, valid columns: "%s"', $offset, implode('", "', array_keys($this->getArrayCopy())) )); } return parent::offsetGet($offset); }
[ "public", "function", "offsetGet", "(", "$", "offset", ")", "{", "if", "(", "!", "$", "this", "->", "offsetExists", "(", "$", "offset", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Column \"%s\" does not exist, valid columns: \"%s\"'", ",", "$", "offset", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "this", "->", "getArrayCopy", "(", ")", ")", ")", ")", ")", ";", "}", "return", "parent", "::", "offsetGet", "(", "$", "offset", ")", ";", "}" ]
Return the given offset. Throw an exception if the given offset does not exist. @throws \InvalidArgumentException
[ "Return", "the", "given", "offset", ".", "Throw", "an", "exception", "if", "the", "given", "offset", "does", "not", "exist", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/Table/Row.php#L31-L41
train
phpbench/phpbench
lib/Formatter/FormatRegistry.php
FormatRegistry.register
public function register($name, FormatInterface $format) { if (isset($this->formats[$name])) { throw new \InvalidArgumentException(sprintf( 'Formatter with name "%s" is already registered', $name )); } $this->formats[$name] = $format; }
php
public function register($name, FormatInterface $format) { if (isset($this->formats[$name])) { throw new \InvalidArgumentException(sprintf( 'Formatter with name "%s" is already registered', $name )); } $this->formats[$name] = $format; }
[ "public", "function", "register", "(", "$", "name", ",", "FormatInterface", "$", "format", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "formats", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Formatter with name \"%s\" is already registered'", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "formats", "[", "$", "name", "]", "=", "$", "format", ";", "}" ]
Register a format class. @param string $name @param FormatInterface $format
[ "Register", "a", "format", "class", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Formatter/FormatRegistry.php#L28-L38
train
phpbench/phpbench
lib/Formatter/FormatRegistry.php
FormatRegistry.get
public function get($name) { if (!isset($this->formats[$name])) { throw new \InvalidArgumentException(sprintf( 'Unknown format "%s", known formats: "%s"', $name, implode(', ', array_keys($this->formats)) )); } return $this->formats[$name]; }
php
public function get($name) { if (!isset($this->formats[$name])) { throw new \InvalidArgumentException(sprintf( 'Unknown format "%s", known formats: "%s"', $name, implode(', ', array_keys($this->formats)) )); } return $this->formats[$name]; }
[ "public", "function", "get", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "formats", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unknown format \"%s\", known formats: \"%s\"'", ",", "$", "name", ",", "implode", "(", "', '", ",", "array_keys", "(", "$", "this", "->", "formats", ")", ")", ")", ")", ";", "}", "return", "$", "this", "->", "formats", "[", "$", "name", "]", ";", "}" ]
Return the named format class. @param string $name @throws \InvalidArgumentException When no formatter exists. @return FormatInterface
[ "Return", "the", "named", "format", "class", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Formatter/FormatRegistry.php#L49-L59
train
phpbench/phpbench
lib/Serializer/XmlEncoder.php
XmlEncoder.encode
public function encode(SuiteCollection $suiteCollection) { $dom = new Document(); $rootEl = $dom->createRoot('phpbench'); $rootEl->setAttribute('version', PhpBench::VERSION); $rootEl->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance' ); foreach ($suiteCollection->getSuites() as $suite) { $suiteEl = $rootEl->appendElement('suite'); $suiteEl->setAttribute('tag', $suite->getTag()); // @deprecated context is deprecated and replaced by `tag`, to be // removed in version 1.0 $suiteEl->setAttribute('context', $suite->getTag()); $suiteEl->setAttribute('date', $suite->getDate()->format('c')); $suiteEl->setAttribute('config-path', $suite->getConfigPath()); $suiteEl->setAttribute('uuid', $suite->getUuid()); $envEl = $suiteEl->appendElement('env'); foreach ($suite->getEnvInformations() as $information) { $infoEl = $envEl->appendElement($information->getName()); foreach ($information as $key => $value) { $infoEl->setAttribute($key, $value); } } foreach ($suite->getBenchmarks() as $benchmark) { $this->processBenchmark($benchmark, $suiteEl); } } return $dom; }
php
public function encode(SuiteCollection $suiteCollection) { $dom = new Document(); $rootEl = $dom->createRoot('phpbench'); $rootEl->setAttribute('version', PhpBench::VERSION); $rootEl->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance' ); foreach ($suiteCollection->getSuites() as $suite) { $suiteEl = $rootEl->appendElement('suite'); $suiteEl->setAttribute('tag', $suite->getTag()); // @deprecated context is deprecated and replaced by `tag`, to be // removed in version 1.0 $suiteEl->setAttribute('context', $suite->getTag()); $suiteEl->setAttribute('date', $suite->getDate()->format('c')); $suiteEl->setAttribute('config-path', $suite->getConfigPath()); $suiteEl->setAttribute('uuid', $suite->getUuid()); $envEl = $suiteEl->appendElement('env'); foreach ($suite->getEnvInformations() as $information) { $infoEl = $envEl->appendElement($information->getName()); foreach ($information as $key => $value) { $infoEl->setAttribute($key, $value); } } foreach ($suite->getBenchmarks() as $benchmark) { $this->processBenchmark($benchmark, $suiteEl); } } return $dom; }
[ "public", "function", "encode", "(", "SuiteCollection", "$", "suiteCollection", ")", "{", "$", "dom", "=", "new", "Document", "(", ")", ";", "$", "rootEl", "=", "$", "dom", "->", "createRoot", "(", "'phpbench'", ")", ";", "$", "rootEl", "->", "setAttribute", "(", "'version'", ",", "PhpBench", "::", "VERSION", ")", ";", "$", "rootEl", "->", "setAttributeNS", "(", "'http://www.w3.org/2000/xmlns/'", ",", "'xmlns:xsi'", ",", "'http://www.w3.org/2001/XMLSchema-instance'", ")", ";", "foreach", "(", "$", "suiteCollection", "->", "getSuites", "(", ")", "as", "$", "suite", ")", "{", "$", "suiteEl", "=", "$", "rootEl", "->", "appendElement", "(", "'suite'", ")", ";", "$", "suiteEl", "->", "setAttribute", "(", "'tag'", ",", "$", "suite", "->", "getTag", "(", ")", ")", ";", "// @deprecated context is deprecated and replaced by `tag`, to be", "// removed in version 1.0", "$", "suiteEl", "->", "setAttribute", "(", "'context'", ",", "$", "suite", "->", "getTag", "(", ")", ")", ";", "$", "suiteEl", "->", "setAttribute", "(", "'date'", ",", "$", "suite", "->", "getDate", "(", ")", "->", "format", "(", "'c'", ")", ")", ";", "$", "suiteEl", "->", "setAttribute", "(", "'config-path'", ",", "$", "suite", "->", "getConfigPath", "(", ")", ")", ";", "$", "suiteEl", "->", "setAttribute", "(", "'uuid'", ",", "$", "suite", "->", "getUuid", "(", ")", ")", ";", "$", "envEl", "=", "$", "suiteEl", "->", "appendElement", "(", "'env'", ")", ";", "foreach", "(", "$", "suite", "->", "getEnvInformations", "(", ")", "as", "$", "information", ")", "{", "$", "infoEl", "=", "$", "envEl", "->", "appendElement", "(", "$", "information", "->", "getName", "(", ")", ")", ";", "foreach", "(", "$", "information", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "infoEl", "->", "setAttribute", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "foreach", "(", "$", "suite", "->", "getBenchmarks", "(", ")", "as", "$", "benchmark", ")", "{", "$", "this", "->", "processBenchmark", "(", "$", "benchmark", ",", "$", "suiteEl", ")", ";", "}", "}", "return", "$", "dom", ";", "}" ]
Encode a Suite object into a XML document. @param SuiteCollection $suiteCollection @return Document
[ "Encode", "a", "Suite", "object", "into", "a", "XML", "document", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Serializer/XmlEncoder.php#L38-L77
train
phpbench/phpbench
lib/Benchmark/BaselineManager.php
BaselineManager.addBaselineCallable
public function addBaselineCallable($name, $callable) { if (isset($this->callables[$name])) { throw new \InvalidArgumentException(sprintf( 'Baseline callable "%s" has already been registered.', $name )); } if (!is_callable($callable)) { throw new \InvalidArgumentException(sprintf( 'Given baseline "%s" callable "%s" is not callable.', $name, is_string($callable) ? $callable : gettype($callable) )); } $this->callables[$name] = $callable; }
php
public function addBaselineCallable($name, $callable) { if (isset($this->callables[$name])) { throw new \InvalidArgumentException(sprintf( 'Baseline callable "%s" has already been registered.', $name )); } if (!is_callable($callable)) { throw new \InvalidArgumentException(sprintf( 'Given baseline "%s" callable "%s" is not callable.', $name, is_string($callable) ? $callable : gettype($callable) )); } $this->callables[$name] = $callable; }
[ "public", "function", "addBaselineCallable", "(", "$", "name", ",", "$", "callable", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "callables", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Baseline callable \"%s\" has already been registered.'", ",", "$", "name", ")", ")", ";", "}", "if", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Given baseline \"%s\" callable \"%s\" is not callable.'", ",", "$", "name", ",", "is_string", "(", "$", "callable", ")", "?", "$", "callable", ":", "gettype", "(", "$", "callable", ")", ")", ")", ";", "}", "$", "this", "->", "callables", "[", "$", "name", "]", "=", "$", "callable", ";", "}" ]
Add a baseline callable. The callable can be any callable accepted by call_user_func. Throws an invalid argument exception if the name has already been registered. @param string $name @param mixed $callable @throws \InvalidArgumentException
[ "Add", "a", "baseline", "callable", ".", "The", "callable", "can", "be", "any", "callable", "accepted", "by", "call_user_func", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/BaselineManager.php#L45-L62
train
phpbench/phpbench
lib/Benchmark/BaselineManager.php
BaselineManager.benchmark
public function benchmark($name, $revs) { if (!isset($this->callables[$name])) { throw new \InvalidArgumentException(sprintf( 'Unknown baseline callable "%s", known baseline callables: "%s"', $name, implode('", "', array_keys($this->callables)) )); } $start = microtime(true); call_user_func($this->callables[$name], $revs); return (microtime(true) - $start) / $revs * 1E6; }
php
public function benchmark($name, $revs) { if (!isset($this->callables[$name])) { throw new \InvalidArgumentException(sprintf( 'Unknown baseline callable "%s", known baseline callables: "%s"', $name, implode('", "', array_keys($this->callables)) )); } $start = microtime(true); call_user_func($this->callables[$name], $revs); return (microtime(true) - $start) / $revs * 1E6; }
[ "public", "function", "benchmark", "(", "$", "name", ",", "$", "revs", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "callables", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unknown baseline callable \"%s\", known baseline callables: \"%s\"'", ",", "$", "name", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "this", "->", "callables", ")", ")", ")", ")", ";", "}", "$", "start", "=", "microtime", "(", "true", ")", ";", "call_user_func", "(", "$", "this", "->", "callables", "[", "$", "name", "]", ",", "$", "revs", ")", ";", "return", "(", "microtime", "(", "true", ")", "-", "$", "start", ")", "/", "$", "revs", "*", "1E6", ";", "}" ]
Return mean time taken to execute the named baseline callable in microseconds. @return float
[ "Return", "mean", "time", "taken", "to", "execute", "the", "named", "baseline", "callable", "in", "microseconds", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/BaselineManager.php#L70-L83
train
phpbench/phpbench
lib/Report/Renderer/ConsoleRenderer.php
ConsoleRenderer.configureFormatters
private function configureFormatters(OutputFormatterInterface $formatter) { $formatter->setStyle( 'title', new OutputFormatterStyle('white', null, ['bold']) ); $formatter->setStyle( 'subtitle', new OutputFormatterStyle('white', null, []) ); $formatter->setStyle( 'description', new OutputFormatterStyle(null, null, []) ); }
php
private function configureFormatters(OutputFormatterInterface $formatter) { $formatter->setStyle( 'title', new OutputFormatterStyle('white', null, ['bold']) ); $formatter->setStyle( 'subtitle', new OutputFormatterStyle('white', null, []) ); $formatter->setStyle( 'description', new OutputFormatterStyle(null, null, []) ); }
[ "private", "function", "configureFormatters", "(", "OutputFormatterInterface", "$", "formatter", ")", "{", "$", "formatter", "->", "setStyle", "(", "'title'", ",", "new", "OutputFormatterStyle", "(", "'white'", ",", "null", ",", "[", "'bold'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'subtitle'", ",", "new", "OutputFormatterStyle", "(", "'white'", ",", "null", ",", "[", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'description'", ",", "new", "OutputFormatterStyle", "(", "null", ",", "null", ",", "[", "]", ")", ")", ";", "}" ]
Adds some output formatters. @param OutputFormatterInterface $formatter
[ "Adds", "some", "output", "formatters", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Renderer/ConsoleRenderer.php#L147-L158
train
phpbench/phpbench
lib/Model/Suite.php
Suite.generateUuid
public function generateUuid() { $serialized = serialize($this->envInformations); $this->uuid = dechex($this->getDate()->format('Ymd')) . substr(sha1(implode([ microtime(), $serialized, $this->configPath, ])), 0, -7); }
php
public function generateUuid() { $serialized = serialize($this->envInformations); $this->uuid = dechex($this->getDate()->format('Ymd')) . substr(sha1(implode([ microtime(), $serialized, $this->configPath, ])), 0, -7); }
[ "public", "function", "generateUuid", "(", ")", "{", "$", "serialized", "=", "serialize", "(", "$", "this", "->", "envInformations", ")", ";", "$", "this", "->", "uuid", "=", "dechex", "(", "$", "this", "->", "getDate", "(", ")", "->", "format", "(", "'Ymd'", ")", ")", ".", "substr", "(", "sha1", "(", "implode", "(", "[", "microtime", "(", ")", ",", "$", "serialized", ",", "$", "this", "->", "configPath", ",", "]", ")", ")", ",", "0", ",", "-", "7", ")", ";", "}" ]
Generate a universally unique identifier. The first 7 characters are the year month and in hex, the rest is a truncated sha1 string encoding the environmental information, the microtime and the configuration path.
[ "Generate", "a", "universally", "unique", "identifier", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Suite.php#L238-L246
train
phpbench/phpbench
lib/Model/Benchmark.php
Benchmark.createSubject
public function createSubject($name) { $subject = new Subject($this, $name); $this->subjects[$name] = $subject; return $subject; }
php
public function createSubject($name) { $subject = new Subject($this, $name); $this->subjects[$name] = $subject; return $subject; }
[ "public", "function", "createSubject", "(", "$", "name", ")", "{", "$", "subject", "=", "new", "Subject", "(", "$", "this", ",", "$", "name", ")", ";", "$", "this", "->", "subjects", "[", "$", "name", "]", "=", "$", "subject", ";", "return", "$", "subject", ";", "}" ]
Create and add a subject. @param string $name @return Subject
[ "Create", "and", "add", "a", "subject", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Benchmark.php#L70-L76
train
phpbench/phpbench
lib/Math/Statistics.php
Statistics.stdev
public static function stdev(array $values, $sample = false) { $variance = self::variance($values, $sample); return \sqrt($variance); }
php
public static function stdev(array $values, $sample = false) { $variance = self::variance($values, $sample); return \sqrt($variance); }
[ "public", "static", "function", "stdev", "(", "array", "$", "values", ",", "$", "sample", "=", "false", ")", "{", "$", "variance", "=", "self", "::", "variance", "(", "$", "values", ",", "$", "sample", ")", ";", "return", "\\", "sqrt", "(", "$", "variance", ")", ";", "}" ]
Return the standard deviation of a given population. @param array $values @param bool $sample @return float
[ "Return", "the", "standard", "deviation", "of", "a", "given", "population", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Statistics.php#L28-L33
train
phpbench/phpbench
lib/Math/Statistics.php
Statistics.variance
public static function variance(array $values, $sample = false) { $average = self::mean($values); $sum = 0; foreach ($values as $value) { $diff = pow($value - $average, 2); $sum += $diff; } if (count($values) === 0) { return 0; } $variance = $sum / (count($values) - ($sample ? 1 : 0)); return $variance; }
php
public static function variance(array $values, $sample = false) { $average = self::mean($values); $sum = 0; foreach ($values as $value) { $diff = pow($value - $average, 2); $sum += $diff; } if (count($values) === 0) { return 0; } $variance = $sum / (count($values) - ($sample ? 1 : 0)); return $variance; }
[ "public", "static", "function", "variance", "(", "array", "$", "values", ",", "$", "sample", "=", "false", ")", "{", "$", "average", "=", "self", "::", "mean", "(", "$", "values", ")", ";", "$", "sum", "=", "0", ";", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$", "diff", "=", "pow", "(", "$", "value", "-", "$", "average", ",", "2", ")", ";", "$", "sum", "+=", "$", "diff", ";", "}", "if", "(", "count", "(", "$", "values", ")", "===", "0", ")", "{", "return", "0", ";", "}", "$", "variance", "=", "$", "sum", "/", "(", "count", "(", "$", "values", ")", "-", "(", "$", "sample", "?", "1", ":", "0", ")", ")", ";", "return", "$", "variance", ";", "}" ]
Return the variance for a given population. @param array $values @param bool $sample @return float
[ "Return", "the", "variance", "for", "a", "given", "population", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Statistics.php#L43-L60
train
phpbench/phpbench
lib/Math/Statistics.php
Statistics.kdeMode
public static function kdeMode(array $population, $space = 512, $bandwidth = null): float { if (count($population) === 1) { return current($population); } if (count($population) === 0) { return 0.0; } if (min($population) == max($population)) { return min($population); } $kde = new Kde($population, $bandwidth); $space = self::linspace(min($population), max($population), $space, true); $dist = $kde->evaluate($space); $maxKeys = array_keys($dist, max($dist)); $modes = []; foreach ($maxKeys as $maxKey) { $modes[] = $space[$maxKey]; } $mode = array_sum($modes) / count($modes); return $mode; }
php
public static function kdeMode(array $population, $space = 512, $bandwidth = null): float { if (count($population) === 1) { return current($population); } if (count($population) === 0) { return 0.0; } if (min($population) == max($population)) { return min($population); } $kde = new Kde($population, $bandwidth); $space = self::linspace(min($population), max($population), $space, true); $dist = $kde->evaluate($space); $maxKeys = array_keys($dist, max($dist)); $modes = []; foreach ($maxKeys as $maxKey) { $modes[] = $space[$maxKey]; } $mode = array_sum($modes) / count($modes); return $mode; }
[ "public", "static", "function", "kdeMode", "(", "array", "$", "population", ",", "$", "space", "=", "512", ",", "$", "bandwidth", "=", "null", ")", ":", "float", "{", "if", "(", "count", "(", "$", "population", ")", "===", "1", ")", "{", "return", "current", "(", "$", "population", ")", ";", "}", "if", "(", "count", "(", "$", "population", ")", "===", "0", ")", "{", "return", "0.0", ";", "}", "if", "(", "min", "(", "$", "population", ")", "==", "max", "(", "$", "population", ")", ")", "{", "return", "min", "(", "$", "population", ")", ";", "}", "$", "kde", "=", "new", "Kde", "(", "$", "population", ",", "$", "bandwidth", ")", ";", "$", "space", "=", "self", "::", "linspace", "(", "min", "(", "$", "population", ")", ",", "max", "(", "$", "population", ")", ",", "$", "space", ",", "true", ")", ";", "$", "dist", "=", "$", "kde", "->", "evaluate", "(", "$", "space", ")", ";", "$", "maxKeys", "=", "array_keys", "(", "$", "dist", ",", "max", "(", "$", "dist", ")", ")", ";", "$", "modes", "=", "[", "]", ";", "foreach", "(", "$", "maxKeys", "as", "$", "maxKey", ")", "{", "$", "modes", "[", "]", "=", "$", "space", "[", "$", "maxKey", "]", ";", "}", "$", "mode", "=", "array_sum", "(", "$", "modes", ")", "/", "count", "(", "$", "modes", ")", ";", "return", "$", "mode", ";", "}" ]
Return the mode using the kernel density estimator using the normal distribution. The mode is the point in the kernel density estimate with the highest frequency, i.e. the time which correlates with the highest peak. If there are two or more modes (i.e. bimodal, trimodal, etc) then we could take the average of these modes. NOTE: If the kde estimate of the population is multi-modal (it has two points with exactly the same value) then the mean mode is returned. This is potentially misleading, but When benchmarking this should be a very rare occurance. @param array $population @param int $space @param string $bandwidth
[ "Return", "the", "mode", "using", "the", "kernel", "density", "estimator", "using", "the", "normal", "distribution", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Statistics.php#L105-L133
train
phpbench/phpbench
lib/Math/Statistics.php
Statistics.histogram
public static function histogram(array $values, $steps = 10, $lowerBound = null, $upperBound = null) { $min = $lowerBound ?: min($values); $max = $upperBound ?: max($values); $range = $max - $min; $step = $range / $steps; $steps++; // add one extra step to catch the max value $histogram = []; $floor = $min; for ($i = 0; $i < $steps; $i++) { $ceil = $floor + $step; if (!isset($histogram[(string) $floor])) { $histogram[(string) $floor] = 0; } foreach ($values as $value) { if ($value >= $floor && $value < $ceil) { $histogram[(string) $floor]++; } } $floor += $step; $ceil += $step; } return $histogram; }
php
public static function histogram(array $values, $steps = 10, $lowerBound = null, $upperBound = null) { $min = $lowerBound ?: min($values); $max = $upperBound ?: max($values); $range = $max - $min; $step = $range / $steps; $steps++; // add one extra step to catch the max value $histogram = []; $floor = $min; for ($i = 0; $i < $steps; $i++) { $ceil = $floor + $step; if (!isset($histogram[(string) $floor])) { $histogram[(string) $floor] = 0; } foreach ($values as $value) { if ($value >= $floor && $value < $ceil) { $histogram[(string) $floor]++; } } $floor += $step; $ceil += $step; } return $histogram; }
[ "public", "static", "function", "histogram", "(", "array", "$", "values", ",", "$", "steps", "=", "10", ",", "$", "lowerBound", "=", "null", ",", "$", "upperBound", "=", "null", ")", "{", "$", "min", "=", "$", "lowerBound", "?", ":", "min", "(", "$", "values", ")", ";", "$", "max", "=", "$", "upperBound", "?", ":", "max", "(", "$", "values", ")", ";", "$", "range", "=", "$", "max", "-", "$", "min", ";", "$", "step", "=", "$", "range", "/", "$", "steps", ";", "$", "steps", "++", ";", "// add one extra step to catch the max value", "$", "histogram", "=", "[", "]", ";", "$", "floor", "=", "$", "min", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "steps", ";", "$", "i", "++", ")", "{", "$", "ceil", "=", "$", "floor", "+", "$", "step", ";", "if", "(", "!", "isset", "(", "$", "histogram", "[", "(", "string", ")", "$", "floor", "]", ")", ")", "{", "$", "histogram", "[", "(", "string", ")", "$", "floor", "]", "=", "0", ";", "}", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "if", "(", "$", "value", ">=", "$", "floor", "&&", "$", "value", "<", "$", "ceil", ")", "{", "$", "histogram", "[", "(", "string", ")", "$", "floor", "]", "++", ";", "}", "}", "$", "floor", "+=", "$", "step", ";", "$", "ceil", "+=", "$", "step", ";", "}", "return", "$", "histogram", ";", "}" ]
Generate a histogram. Note this is not a great function, and should not be relied upon for serious use. For a better implementation copy: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.histogram.html @param array $values @param int $steps @param float $lowerBound @param float $upperBound @return array
[ "Generate", "a", "histogram", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Math/Statistics.php#L185-L217
train
phpbench/phpbench
lib/Model/Variant.php
Variant.createIteration
public function createIteration(array $results = []) { $index = count($this->iterations); $iteration = new Iteration($index, $this, $results); $this->iterations[] = $iteration; return $iteration; }
php
public function createIteration(array $results = []) { $index = count($this->iterations); $iteration = new Iteration($index, $this, $results); $this->iterations[] = $iteration; return $iteration; }
[ "public", "function", "createIteration", "(", "array", "$", "results", "=", "[", "]", ")", "{", "$", "index", "=", "count", "(", "$", "this", "->", "iterations", ")", ";", "$", "iteration", "=", "new", "Iteration", "(", "$", "index", ",", "$", "this", ",", "$", "results", ")", ";", "$", "this", "->", "iterations", "[", "]", "=", "$", "iteration", ";", "return", "$", "iteration", ";", "}" ]
Create and add a new iteration. @param array $results @return Iteration
[ "Create", "and", "add", "a", "new", "iteration", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L128-L135
train
phpbench/phpbench
lib/Model/Variant.php
Variant.getMetricValues
public function getMetricValues($resultClass, $metricName) { $values = []; foreach ($this->iterations as $iteration) { if ($iteration->hasResult($resultClass)) { $values[] = $iteration->getMetric($resultClass, $metricName); } } return $values; }
php
public function getMetricValues($resultClass, $metricName) { $values = []; foreach ($this->iterations as $iteration) { if ($iteration->hasResult($resultClass)) { $values[] = $iteration->getMetric($resultClass, $metricName); } } return $values; }
[ "public", "function", "getMetricValues", "(", "$", "resultClass", ",", "$", "metricName", ")", "{", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "iterations", "as", "$", "iteration", ")", "{", "if", "(", "$", "iteration", "->", "hasResult", "(", "$", "resultClass", ")", ")", "{", "$", "values", "[", "]", "=", "$", "iteration", "->", "getMetric", "(", "$", "resultClass", ",", "$", "metricName", ")", ";", "}", "}", "return", "$", "values", ";", "}" ]
Return result values by class and metric name. e.g. ``` $variant->getMetricValues(ComputedResult::class, 'z_value'); ``` @return mixed[]
[ "Return", "result", "values", "by", "class", "and", "metric", "name", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L176-L187
train
phpbench/phpbench
lib/Model/Variant.php
Variant.getMetricValuesByRev
public function getMetricValuesByRev($resultClass, $metric) { return array_map(function ($value) { return $value / $this->getRevolutions(); }, $this->getMetricValues($resultClass, $metric)); }
php
public function getMetricValuesByRev($resultClass, $metric) { return array_map(function ($value) { return $value / $this->getRevolutions(); }, $this->getMetricValues($resultClass, $metric)); }
[ "public", "function", "getMetricValuesByRev", "(", "$", "resultClass", ",", "$", "metric", ")", "{", "return", "array_map", "(", "function", "(", "$", "value", ")", "{", "return", "$", "value", "/", "$", "this", "->", "getRevolutions", "(", ")", ";", "}", ",", "$", "this", "->", "getMetricValues", "(", "$", "resultClass", ",", "$", "metric", ")", ")", ";", "}" ]
Return the average metric values by revolution. @return mixed[]
[ "Return", "the", "average", "metric", "values", "by", "revolution", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L194-L199
train
phpbench/phpbench
lib/Model/Variant.php
Variant.computeStats
public function computeStats() { $this->rejects = []; $revs = $this->getRevolutions(); if (0 === count($this->iterations)) { return; } $times = $this->getMetricValuesByRev(TimeResult::class, 'net'); $retryThreshold = $this->getSubject()->getRetryThreshold(); $this->stats = new Distribution($times, $this->computedStats); foreach ($this->iterations as $iteration) { $timeResult = $iteration->getResult(TimeResult::class); assert($timeResult instanceof TimeResult); // deviation is the percentage different of the value from the mean of the set. if ($this->stats->getMean() > 0) { $deviation = 100 / $this->stats->getMean() * ( ( $timeResult->getRevTime($iteration->getVariant()->getRevolutions()) ) - $this->stats->getMean() ); } else { $deviation = 0; } // the Z-Value represents the number of standard deviations this // value is away from the mean. $revTime = $timeResult->getRevTime($revs); $zValue = $this->stats->getStdev() ? ($revTime - $this->stats->getMean()) / $this->stats->getStdev() : 0; if (null !== $retryThreshold) { if (abs($deviation) >= $retryThreshold) { $this->rejects[] = $iteration; } } $iteration->setResult(new ComputedResult($zValue, $deviation)); } $this->computed = true; }
php
public function computeStats() { $this->rejects = []; $revs = $this->getRevolutions(); if (0 === count($this->iterations)) { return; } $times = $this->getMetricValuesByRev(TimeResult::class, 'net'); $retryThreshold = $this->getSubject()->getRetryThreshold(); $this->stats = new Distribution($times, $this->computedStats); foreach ($this->iterations as $iteration) { $timeResult = $iteration->getResult(TimeResult::class); assert($timeResult instanceof TimeResult); // deviation is the percentage different of the value from the mean of the set. if ($this->stats->getMean() > 0) { $deviation = 100 / $this->stats->getMean() * ( ( $timeResult->getRevTime($iteration->getVariant()->getRevolutions()) ) - $this->stats->getMean() ); } else { $deviation = 0; } // the Z-Value represents the number of standard deviations this // value is away from the mean. $revTime = $timeResult->getRevTime($revs); $zValue = $this->stats->getStdev() ? ($revTime - $this->stats->getMean()) / $this->stats->getStdev() : 0; if (null !== $retryThreshold) { if (abs($deviation) >= $retryThreshold) { $this->rejects[] = $iteration; } } $iteration->setResult(new ComputedResult($zValue, $deviation)); } $this->computed = true; }
[ "public", "function", "computeStats", "(", ")", "{", "$", "this", "->", "rejects", "=", "[", "]", ";", "$", "revs", "=", "$", "this", "->", "getRevolutions", "(", ")", ";", "if", "(", "0", "===", "count", "(", "$", "this", "->", "iterations", ")", ")", "{", "return", ";", "}", "$", "times", "=", "$", "this", "->", "getMetricValuesByRev", "(", "TimeResult", "::", "class", ",", "'net'", ")", ";", "$", "retryThreshold", "=", "$", "this", "->", "getSubject", "(", ")", "->", "getRetryThreshold", "(", ")", ";", "$", "this", "->", "stats", "=", "new", "Distribution", "(", "$", "times", ",", "$", "this", "->", "computedStats", ")", ";", "foreach", "(", "$", "this", "->", "iterations", "as", "$", "iteration", ")", "{", "$", "timeResult", "=", "$", "iteration", "->", "getResult", "(", "TimeResult", "::", "class", ")", ";", "assert", "(", "$", "timeResult", "instanceof", "TimeResult", ")", ";", "// deviation is the percentage different of the value from the mean of the set.", "if", "(", "$", "this", "->", "stats", "->", "getMean", "(", ")", ">", "0", ")", "{", "$", "deviation", "=", "100", "/", "$", "this", "->", "stats", "->", "getMean", "(", ")", "*", "(", "(", "$", "timeResult", "->", "getRevTime", "(", "$", "iteration", "->", "getVariant", "(", ")", "->", "getRevolutions", "(", ")", ")", ")", "-", "$", "this", "->", "stats", "->", "getMean", "(", ")", ")", ";", "}", "else", "{", "$", "deviation", "=", "0", ";", "}", "// the Z-Value represents the number of standard deviations this", "// value is away from the mean.", "$", "revTime", "=", "$", "timeResult", "->", "getRevTime", "(", "$", "revs", ")", ";", "$", "zValue", "=", "$", "this", "->", "stats", "->", "getStdev", "(", ")", "?", "(", "$", "revTime", "-", "$", "this", "->", "stats", "->", "getMean", "(", ")", ")", "/", "$", "this", "->", "stats", "->", "getStdev", "(", ")", ":", "0", ";", "if", "(", "null", "!==", "$", "retryThreshold", ")", "{", "if", "(", "abs", "(", "$", "deviation", ")", ">=", "$", "retryThreshold", ")", "{", "$", "this", "->", "rejects", "[", "]", "=", "$", "iteration", ";", "}", "}", "$", "iteration", "->", "setResult", "(", "new", "ComputedResult", "(", "$", "zValue", ",", "$", "deviation", ")", ")", ";", "}", "$", "this", "->", "computed", "=", "true", ";", "}" ]
Calculate and set the deviation from the mean time for each iteration. If the deviation is greater than the rejection threshold, then mark the iteration as rejected.
[ "Calculate", "and", "set", "the", "deviation", "from", "the", "mean", "time", "for", "each", "iteration", ".", "If", "the", "deviation", "is", "greater", "than", "the", "rejection", "threshold", "then", "mark", "the", "iteration", "as", "rejected", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L212-L255
train
phpbench/phpbench
lib/Model/Variant.php
Variant.getStats
public function getStats() { if (null !== $this->errorStack) { throw new \RuntimeException(sprintf( 'Cannot retrieve stats when an exception was encountered ([%s] %s)', $this->errorStack->getTop()->getClass(), $this->errorStack->getTop()->getMessage() )); } if (false === $this->computed) { throw new \RuntimeException( 'No statistics have yet been computed for this iteration set (::computeStats should be called)' ); } return $this->stats; }
php
public function getStats() { if (null !== $this->errorStack) { throw new \RuntimeException(sprintf( 'Cannot retrieve stats when an exception was encountered ([%s] %s)', $this->errorStack->getTop()->getClass(), $this->errorStack->getTop()->getMessage() )); } if (false === $this->computed) { throw new \RuntimeException( 'No statistics have yet been computed for this iteration set (::computeStats should be called)' ); } return $this->stats; }
[ "public", "function", "getStats", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "errorStack", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Cannot retrieve stats when an exception was encountered ([%s] %s)'", ",", "$", "this", "->", "errorStack", "->", "getTop", "(", ")", "->", "getClass", "(", ")", ",", "$", "this", "->", "errorStack", "->", "getTop", "(", ")", "->", "getMessage", "(", ")", ")", ")", ";", "}", "if", "(", "false", "===", "$", "this", "->", "computed", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No statistics have yet been computed for this iteration set (::computeStats should be called)'", ")", ";", "}", "return", "$", "this", "->", "stats", ";", "}" ]
Return statistics about this iteration collection. See self::$stats. TODO: Rename to getDistribution @return Distribution
[ "Return", "statistics", "about", "this", "iteration", "collection", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L286-L303
train
phpbench/phpbench
lib/Model/Variant.php
Variant.setException
public function setException(\Exception $exception) { $errors = []; do { $errors[] = Error::fromException($exception); } while ($exception = $exception->getPrevious()); $this->errorStack = new ErrorStack($this, $errors); }
php
public function setException(\Exception $exception) { $errors = []; do { $errors[] = Error::fromException($exception); } while ($exception = $exception->getPrevious()); $this->errorStack = new ErrorStack($this, $errors); }
[ "public", "function", "setException", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "errors", "=", "[", "]", ";", "do", "{", "$", "errors", "[", "]", "=", "Error", "::", "fromException", "(", "$", "exception", ")", ";", "}", "while", "(", "$", "exception", "=", "$", "exception", "->", "getPrevious", "(", ")", ")", ";", "$", "this", "->", "errorStack", "=", "new", "ErrorStack", "(", "$", "this", ",", "$", "errors", ")", ";", "}" ]
Create an error stack from an Exception. Should be called when an Exception is encountered during the execution of any of the iteration processes. After an exception is encountered the results from this iteration set are invalid. @param \Exception $exception
[ "Create", "an", "error", "stack", "from", "an", "Exception", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Variant.php#L372-L381
train
phpbench/phpbench
lib/Assertion/AssertionProcessor.php
AssertionProcessor.assertionsFromRawCliConfig
public function assertionsFromRawCliConfig(array $rawAssertions) { $assertions = []; foreach ($rawAssertions as $rawAssertion) { $config = $this->jsonDecoder->decode($rawAssertion); $assertions[] = new AssertionMetadata($config); } return $assertions; }
php
public function assertionsFromRawCliConfig(array $rawAssertions) { $assertions = []; foreach ($rawAssertions as $rawAssertion) { $config = $this->jsonDecoder->decode($rawAssertion); $assertions[] = new AssertionMetadata($config); } return $assertions; }
[ "public", "function", "assertionsFromRawCliConfig", "(", "array", "$", "rawAssertions", ")", "{", "$", "assertions", "=", "[", "]", ";", "foreach", "(", "$", "rawAssertions", "as", "$", "rawAssertion", ")", "{", "$", "config", "=", "$", "this", "->", "jsonDecoder", "->", "decode", "(", "$", "rawAssertion", ")", ";", "$", "assertions", "[", "]", "=", "new", "AssertionMetadata", "(", "$", "config", ")", ";", "}", "return", "$", "assertions", ";", "}" ]
Return an array of assertion metadatas from the raw JSON-like stuff from the CLI.
[ "Return", "an", "array", "of", "assertion", "metadatas", "from", "the", "raw", "JSON", "-", "like", "stuff", "from", "the", "CLI", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Assertion/AssertionProcessor.php#L51-L61
train
phpbench/phpbench
lib/Registry/Registry.php
Registry.registerService
public function registerService($name, $serviceId) { if (isset($this->serviceMap[$name])) { throw new \InvalidArgumentException(sprintf( '%s service "%s" is already registered', $this->serviceType, $name )); } $this->serviceMap[$name] = $serviceId; $this->services[$name] = null; }
php
public function registerService($name, $serviceId) { if (isset($this->serviceMap[$name])) { throw new \InvalidArgumentException(sprintf( '%s service "%s" is already registered', $this->serviceType, $name )); } $this->serviceMap[$name] = $serviceId; $this->services[$name] = null; }
[ "public", "function", "registerService", "(", "$", "name", ",", "$", "serviceId", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "serviceMap", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'%s service \"%s\" is already registered'", ",", "$", "this", "->", "serviceType", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "serviceMap", "[", "$", "name", "]", "=", "$", "serviceId", ";", "$", "this", "->", "services", "[", "$", "name", "]", "=", "null", ";", "}" ]
Register a service ID with against the given name. @param string $name @param string $serviceId
[ "Register", "a", "service", "ID", "with", "against", "the", "given", "name", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Registry/Registry.php#L52-L63
train
phpbench/phpbench
lib/Registry/Registry.php
Registry.setService
public function setService($name, $object) { if (isset($this->services[$name])) { throw new \InvalidArgumentException(sprintf( '%s service "%s" already exists.', $this->serviceType, $name )); } $this->services[$name] = $object; }
php
public function setService($name, $object) { if (isset($this->services[$name])) { throw new \InvalidArgumentException(sprintf( '%s service "%s" already exists.', $this->serviceType, $name )); } $this->services[$name] = $object; }
[ "public", "function", "setService", "(", "$", "name", ",", "$", "object", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "services", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'%s service \"%s\" already exists.'", ",", "$", "this", "->", "serviceType", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "services", "[", "$", "name", "]", "=", "$", "object", ";", "}" ]
Directly set a named service. @param string $name @param object $object
[ "Directly", "set", "a", "named", "service", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Registry/Registry.php#L71-L82
train
phpbench/phpbench
lib/Registry/Registry.php
Registry.getService
public function getService($name = null) { $name = $name ?: $this->defaultService; if (!$name) { throw new \RuntimeException(sprintf( 'You must configure a default %s service, registered %s services: "%s"', $this->serviceType, $this->serviceType, implode('", "', array_keys($this->services)) )); } if (isset($this->services[$name])) { return $this->services[$name]; } $this->assertServiceExists($name); $this->services[$name] = $this->container->get($this->serviceMap[$name]); return $this->services[$name]; }
php
public function getService($name = null) { $name = $name ?: $this->defaultService; if (!$name) { throw new \RuntimeException(sprintf( 'You must configure a default %s service, registered %s services: "%s"', $this->serviceType, $this->serviceType, implode('", "', array_keys($this->services)) )); } if (isset($this->services[$name])) { return $this->services[$name]; } $this->assertServiceExists($name); $this->services[$name] = $this->container->get($this->serviceMap[$name]); return $this->services[$name]; }
[ "public", "function", "getService", "(", "$", "name", "=", "null", ")", "{", "$", "name", "=", "$", "name", "?", ":", "$", "this", "->", "defaultService", ";", "if", "(", "!", "$", "name", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'You must configure a default %s service, registered %s services: \"%s\"'", ",", "$", "this", "->", "serviceType", ",", "$", "this", "->", "serviceType", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "this", "->", "services", ")", ")", ")", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "services", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "services", "[", "$", "name", "]", ";", "}", "$", "this", "->", "assertServiceExists", "(", "$", "name", ")", ";", "$", "this", "->", "services", "[", "$", "name", "]", "=", "$", "this", "->", "container", "->", "get", "(", "$", "this", "->", "serviceMap", "[", "$", "name", "]", ")", ";", "return", "$", "this", "->", "services", "[", "$", "name", "]", ";", "}" ]
Return the named service, lazily creating it from the container if it has not yet been accessed. @param string $name @return object
[ "Return", "the", "named", "service", "lazily", "creating", "it", "from", "the", "container", "if", "it", "has", "not", "yet", "been", "accessed", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Registry/Registry.php#L92-L112
train
phpbench/phpbench
lib/Benchmark/Metadata/AnnotationReader.php
AnnotationReader.parse
private function parse($input, $context = '') { try { $annotations = $this->docParser->parse($input, $context); } catch (AnnotationException $e) { if (!preg_match('/The annotation "(.*)" .* was never imported/', $e->getMessage(), $matches)) { throw $e; } throw new \InvalidArgumentException(sprintf( 'Unrecognized annotation %s, valid PHPBench annotations: @%s', $matches[1], implode(', @', array_keys(self::$phpBenchImports)) ), 0, $e); } return $annotations; }
php
private function parse($input, $context = '') { try { $annotations = $this->docParser->parse($input, $context); } catch (AnnotationException $e) { if (!preg_match('/The annotation "(.*)" .* was never imported/', $e->getMessage(), $matches)) { throw $e; } throw new \InvalidArgumentException(sprintf( 'Unrecognized annotation %s, valid PHPBench annotations: @%s', $matches[1], implode(', @', array_keys(self::$phpBenchImports)) ), 0, $e); } return $annotations; }
[ "private", "function", "parse", "(", "$", "input", ",", "$", "context", "=", "''", ")", "{", "try", "{", "$", "annotations", "=", "$", "this", "->", "docParser", "->", "parse", "(", "$", "input", ",", "$", "context", ")", ";", "}", "catch", "(", "AnnotationException", "$", "e", ")", "{", "if", "(", "!", "preg_match", "(", "'/The annotation \"(.*)\" .* was never imported/'", ",", "$", "e", "->", "getMessage", "(", ")", ",", "$", "matches", ")", ")", "{", "throw", "$", "e", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unrecognized annotation %s, valid PHPBench annotations: @%s'", ",", "$", "matches", "[", "1", "]", ",", "implode", "(", "', @'", ",", "array_keys", "(", "self", "::", "$", "phpBenchImports", ")", ")", ")", ",", "0", ",", "$", "e", ")", ";", "}", "return", "$", "annotations", ";", "}" ]
Delegates to the doctrine DocParser but catches annotation not found errors and throws something useful. @see \Doctrine\Common\Annotations\DocParser
[ "Delegates", "to", "the", "doctrine", "DocParser", "but", "catches", "annotation", "not", "found", "errors", "and", "throws", "something", "useful", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Metadata/AnnotationReader.php#L209-L226
train
phpbench/phpbench
lib/Benchmark/Metadata/BenchmarkMetadata.php
BenchmarkMetadata.getOrCreateSubject
public function getOrCreateSubject($name) { if (isset($this->subjects[$name])) { return $this->subjects[$name]; } $this->subjects[$name] = new SubjectMetadata($this, $name); return $this->subjects[$name]; }
php
public function getOrCreateSubject($name) { if (isset($this->subjects[$name])) { return $this->subjects[$name]; } $this->subjects[$name] = new SubjectMetadata($this, $name); return $this->subjects[$name]; }
[ "public", "function", "getOrCreateSubject", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "subjects", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "subjects", "[", "$", "name", "]", ";", "}", "$", "this", "->", "subjects", "[", "$", "name", "]", "=", "new", "SubjectMetadata", "(", "$", "this", ",", "$", "name", ")", ";", "return", "$", "this", "->", "subjects", "[", "$", "name", "]", ";", "}" ]
Get or create a new SubjectMetadata instance with the given name. @param string $name @return SubjectMetadata
[ "Get", "or", "create", "a", "new", "SubjectMetadata", "instance", "with", "the", "given", "name", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Metadata/BenchmarkMetadata.php#L77-L86
train
phpbench/phpbench
lib/Benchmark/Metadata/BenchmarkMetadata.php
BenchmarkMetadata.filterSubjectNames
public function filterSubjectNames(array $filters) { foreach (array_keys($this->subjects) as $subjectName) { $unset = true; foreach ($filters as $filter) { if (preg_match( sprintf('{^.*?%s.*?$}', $filter), sprintf('%s::%s', $this->getClass(), $subjectName) )) { $unset = false; break; } } if (true === $unset) { unset($this->subjects[$subjectName]); } } }
php
public function filterSubjectNames(array $filters) { foreach (array_keys($this->subjects) as $subjectName) { $unset = true; foreach ($filters as $filter) { if (preg_match( sprintf('{^.*?%s.*?$}', $filter), sprintf('%s::%s', $this->getClass(), $subjectName) )) { $unset = false; break; } } if (true === $unset) { unset($this->subjects[$subjectName]); } } }
[ "public", "function", "filterSubjectNames", "(", "array", "$", "filters", ")", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "subjects", ")", "as", "$", "subjectName", ")", "{", "$", "unset", "=", "true", ";", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "if", "(", "preg_match", "(", "sprintf", "(", "'{^.*?%s.*?$}'", ",", "$", "filter", ")", ",", "sprintf", "(", "'%s::%s'", ",", "$", "this", "->", "getClass", "(", ")", ",", "$", "subjectName", ")", ")", ")", "{", "$", "unset", "=", "false", ";", "break", ";", "}", "}", "if", "(", "true", "===", "$", "unset", ")", "{", "unset", "(", "$", "this", "->", "subjects", "[", "$", "subjectName", "]", ")", ";", "}", "}", "}" ]
Remove all subjects whose name is not in the given list. @param string[] $filters
[ "Remove", "all", "subjects", "whose", "name", "is", "not", "in", "the", "given", "list", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Metadata/BenchmarkMetadata.php#L103-L123
train
phpbench/phpbench
lib/Benchmark/Metadata/BenchmarkMetadata.php
BenchmarkMetadata.filterSubjectGroups
public function filterSubjectGroups(array $groups) { foreach ($this->subjects as $subjectName => $subject) { if (0 === count(array_intersect($subject->getGroups(), $groups))) { unset($this->subjects[$subjectName]); } } }
php
public function filterSubjectGroups(array $groups) { foreach ($this->subjects as $subjectName => $subject) { if (0 === count(array_intersect($subject->getGroups(), $groups))) { unset($this->subjects[$subjectName]); } } }
[ "public", "function", "filterSubjectGroups", "(", "array", "$", "groups", ")", "{", "foreach", "(", "$", "this", "->", "subjects", "as", "$", "subjectName", "=>", "$", "subject", ")", "{", "if", "(", "0", "===", "count", "(", "array_intersect", "(", "$", "subject", "->", "getGroups", "(", ")", ",", "$", "groups", ")", ")", ")", "{", "unset", "(", "$", "this", "->", "subjects", "[", "$", "subjectName", "]", ")", ";", "}", "}", "}" ]
Remove all the subjects which are not contained in the given list of groups. @param string[] $groups
[ "Remove", "all", "the", "subjects", "which", "are", "not", "contained", "in", "the", "given", "list", "of", "groups", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Metadata/BenchmarkMetadata.php#L130-L137
train
phpbench/phpbench
lib/Registry/ConfigurableRegistry.php
ConfigurableRegistry.getConfig
public function getConfig($name) { if (is_array($name)) { $config = $name; $name = uniqid(); $this->setConfig($name, $config); } $name = trim($name); $name = $this->processRawCliConfig($name); if (!isset($this->configs[$name])) { throw new \InvalidArgumentException(sprintf( 'No %s configuration named "%s" exists. Known configurations: "%s"', $this->serviceType, $name, implode('", "', array_keys($this->configs)) )); } if (!isset($this->resolvedConfigs[$name])) { $this->resolveConfig($name); } return $this->resolvedConfigs[$name]; }
php
public function getConfig($name) { if (is_array($name)) { $config = $name; $name = uniqid(); $this->setConfig($name, $config); } $name = trim($name); $name = $this->processRawCliConfig($name); if (!isset($this->configs[$name])) { throw new \InvalidArgumentException(sprintf( 'No %s configuration named "%s" exists. Known configurations: "%s"', $this->serviceType, $name, implode('", "', array_keys($this->configs)) )); } if (!isset($this->resolvedConfigs[$name])) { $this->resolveConfig($name); } return $this->resolvedConfigs[$name]; }
[ "public", "function", "getConfig", "(", "$", "name", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "$", "config", "=", "$", "name", ";", "$", "name", "=", "uniqid", "(", ")", ";", "$", "this", "->", "setConfig", "(", "$", "name", ",", "$", "config", ")", ";", "}", "$", "name", "=", "trim", "(", "$", "name", ")", ";", "$", "name", "=", "$", "this", "->", "processRawCliConfig", "(", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "configs", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'No %s configuration named \"%s\" exists. Known configurations: \"%s\"'", ",", "$", "this", "->", "serviceType", ",", "$", "name", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "this", "->", "configs", ")", ")", ")", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "resolvedConfigs", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "resolveConfig", "(", "$", "name", ")", ";", "}", "return", "$", "this", "->", "resolvedConfigs", "[", "$", "name", "]", ";", "}" ]
Return the named configuration. @return Config
[ "Return", "the", "named", "configuration", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Registry/ConfigurableRegistry.php#L54-L79
train
phpbench/phpbench
lib/Registry/ConfigurableRegistry.php
ConfigurableRegistry.setConfig
public function setConfig($name, array $config) { if (isset($this->configs[$name])) { throw new \InvalidArgumentException(sprintf( '%s config "%s" already exists.', $this->serviceType, $name )); } $this->configs[$name] = $config; }
php
public function setConfig($name, array $config) { if (isset($this->configs[$name])) { throw new \InvalidArgumentException(sprintf( '%s config "%s" already exists.', $this->serviceType, $name )); } $this->configs[$name] = $config; }
[ "public", "function", "setConfig", "(", "$", "name", ",", "array", "$", "config", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "configs", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'%s config \"%s\" already exists.'", ",", "$", "this", "->", "serviceType", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "configs", "[", "$", "name", "]", "=", "$", "config", ";", "}" ]
Set a named configuration. Note that all configurations must be associated with a named service via a configuration key equal to the configuration service type of this registry. @param string $name @param array $config
[ "Set", "a", "named", "configuration", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Registry/ConfigurableRegistry.php#L90-L101
train
phpbench/phpbench
lib/Environment/Supplier.php
Supplier.getInformations
public function getInformations() { $informations = []; foreach ($this->providers as $provider) { if (false === $provider->isApplicable()) { continue; } $informations[] = $provider->getInformation(); } return $informations; }
php
public function getInformations() { $informations = []; foreach ($this->providers as $provider) { if (false === $provider->isApplicable()) { continue; } $informations[] = $provider->getInformation(); } return $informations; }
[ "public", "function", "getInformations", "(", ")", "{", "$", "informations", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "providers", "as", "$", "provider", ")", "{", "if", "(", "false", "===", "$", "provider", "->", "isApplicable", "(", ")", ")", "{", "continue", ";", "}", "$", "informations", "[", "]", "=", "$", "provider", "->", "getInformation", "(", ")", ";", "}", "return", "$", "informations", ";", "}" ]
Return information from the current environment. @return Information[]
[ "Return", "information", "from", "the", "current", "environment", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Environment/Supplier.php#L45-L58
train
phpbench/phpbench
lib/Storage/Driver/Xml/HistoryIterator.php
HistoryIterator.getEntryIterator
private function getEntryIterator() { $files = $this->days->current(); $files = new \DirectoryIterator($this->days->current()); $historyEntries = []; foreach ($files as $file) { if (!$file->isFile()) { continue; } if ($file->getExtension() !== 'xml') { continue; } $historyEntries[] = $this->getHistoryEntry($file->getPathname()); } usort($historyEntries, function ($entry1, $entry2) { if ($entry1->getDate()->format('U') === $entry2->getDate()->format('U')) { return; } return $entry1->getDate()->format('U') < $entry2->getDate()->format('U'); }); return new \ArrayIterator($historyEntries); }
php
private function getEntryIterator() { $files = $this->days->current(); $files = new \DirectoryIterator($this->days->current()); $historyEntries = []; foreach ($files as $file) { if (!$file->isFile()) { continue; } if ($file->getExtension() !== 'xml') { continue; } $historyEntries[] = $this->getHistoryEntry($file->getPathname()); } usort($historyEntries, function ($entry1, $entry2) { if ($entry1->getDate()->format('U') === $entry2->getDate()->format('U')) { return; } return $entry1->getDate()->format('U') < $entry2->getDate()->format('U'); }); return new \ArrayIterator($historyEntries); }
[ "private", "function", "getEntryIterator", "(", ")", "{", "$", "files", "=", "$", "this", "->", "days", "->", "current", "(", ")", ";", "$", "files", "=", "new", "\\", "DirectoryIterator", "(", "$", "this", "->", "days", "->", "current", "(", ")", ")", ";", "$", "historyEntries", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "if", "(", "!", "$", "file", "->", "isFile", "(", ")", ")", "{", "continue", ";", "}", "if", "(", "$", "file", "->", "getExtension", "(", ")", "!==", "'xml'", ")", "{", "continue", ";", "}", "$", "historyEntries", "[", "]", "=", "$", "this", "->", "getHistoryEntry", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "}", "usort", "(", "$", "historyEntries", ",", "function", "(", "$", "entry1", ",", "$", "entry2", ")", "{", "if", "(", "$", "entry1", "->", "getDate", "(", ")", "->", "format", "(", "'U'", ")", "===", "$", "entry2", "->", "getDate", "(", ")", "->", "format", "(", "'U'", ")", ")", "{", "return", ";", "}", "return", "$", "entry1", "->", "getDate", "(", ")", "->", "format", "(", "'U'", ")", "<", "$", "entry2", "->", "getDate", "(", ")", "->", "format", "(", "'U'", ")", ";", "}", ")", ";", "return", "new", "\\", "ArrayIterator", "(", "$", "historyEntries", ")", ";", "}" ]
Return an iterator for the history entries. We hydrate all of the entries for the "current" day. @return \ArrayIterator
[ "Return", "an", "iterator", "for", "the", "history", "entries", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Storage/Driver/Xml/HistoryIterator.php#L171-L197
train
phpbench/phpbench
lib/Storage/Driver/Xml/HistoryIterator.php
HistoryIterator.getHistoryEntry
private function getHistoryEntry($path) { $dom = new Document(); $dom->load($path); $collection = $this->xmlDecoder->decode($dom); $suites = $collection->getSuites(); $suite = reset($suites); $envInformations = $suite->getEnvInformations(); $vcsBranch = null; if (isset($envInformations['vcs']['branch'])) { $vcsBranch = $envInformations['vcs']['branch']; } $summary = $suite->getSummary(); $entry = new HistoryEntry( $suite->getUuid(), $suite->getDate(), $suite->getTag(), $vcsBranch, $summary->getNbSubjects(), $summary->getNbIterations(), $summary->getNbRevolutions(), $summary->getMinTime(), $summary->getMaxTime(), $summary->getMeanTime(), $summary->getMeanRelStDev(), $summary->getTotalTime() ); return $entry; }
php
private function getHistoryEntry($path) { $dom = new Document(); $dom->load($path); $collection = $this->xmlDecoder->decode($dom); $suites = $collection->getSuites(); $suite = reset($suites); $envInformations = $suite->getEnvInformations(); $vcsBranch = null; if (isset($envInformations['vcs']['branch'])) { $vcsBranch = $envInformations['vcs']['branch']; } $summary = $suite->getSummary(); $entry = new HistoryEntry( $suite->getUuid(), $suite->getDate(), $suite->getTag(), $vcsBranch, $summary->getNbSubjects(), $summary->getNbIterations(), $summary->getNbRevolutions(), $summary->getMinTime(), $summary->getMaxTime(), $summary->getMeanTime(), $summary->getMeanRelStDev(), $summary->getTotalTime() ); return $entry; }
[ "private", "function", "getHistoryEntry", "(", "$", "path", ")", "{", "$", "dom", "=", "new", "Document", "(", ")", ";", "$", "dom", "->", "load", "(", "$", "path", ")", ";", "$", "collection", "=", "$", "this", "->", "xmlDecoder", "->", "decode", "(", "$", "dom", ")", ";", "$", "suites", "=", "$", "collection", "->", "getSuites", "(", ")", ";", "$", "suite", "=", "reset", "(", "$", "suites", ")", ";", "$", "envInformations", "=", "$", "suite", "->", "getEnvInformations", "(", ")", ";", "$", "vcsBranch", "=", "null", ";", "if", "(", "isset", "(", "$", "envInformations", "[", "'vcs'", "]", "[", "'branch'", "]", ")", ")", "{", "$", "vcsBranch", "=", "$", "envInformations", "[", "'vcs'", "]", "[", "'branch'", "]", ";", "}", "$", "summary", "=", "$", "suite", "->", "getSummary", "(", ")", ";", "$", "entry", "=", "new", "HistoryEntry", "(", "$", "suite", "->", "getUuid", "(", ")", ",", "$", "suite", "->", "getDate", "(", ")", ",", "$", "suite", "->", "getTag", "(", ")", ",", "$", "vcsBranch", ",", "$", "summary", "->", "getNbSubjects", "(", ")", ",", "$", "summary", "->", "getNbIterations", "(", ")", ",", "$", "summary", "->", "getNbRevolutions", "(", ")", ",", "$", "summary", "->", "getMinTime", "(", ")", ",", "$", "summary", "->", "getMaxTime", "(", ")", ",", "$", "summary", "->", "getMeanTime", "(", ")", ",", "$", "summary", "->", "getMeanRelStDev", "(", ")", ",", "$", "summary", "->", "getTotalTime", "(", ")", ")", ";", "return", "$", "entry", ";", "}" ]
Hydrate and return the history entry for the given path. The summary *should* used pre-calculated values from the XML therefore reducing the normal overhead, however this code is still quite expensive as we are creating the entire object graph for each suite run. @param string $path @return HistoryEntry
[ "Hydrate", "and", "return", "the", "history", "entry", "for", "the", "given", "path", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Storage/Driver/Xml/HistoryIterator.php#L211-L243
train
phpbench/phpbench
lib/Report/Generator/TableGenerator.php
TableGenerator.processDiffs
private function processDiffs(array $tables, Config $config) { $stat = $config['diff_col']; if ($config['compare']) { return $tables; } if (!in_array('diff', $config['cols'])) { return $tables; } if (!in_array($stat, $config['cols'])) { throw new \InvalidArgumentException(sprintf( 'The "%s" column must be visible when using the diff column', $stat )); } return F\map($tables, function ($table) use ($stat) { $means = F\map($table, function ($row) use ($stat) { return $row[$stat]; }); $min = min($means); return F\map($table, function ($row) use ($min, $stat) { if ($row[$stat] === 0) { $row['diff'] = 0; return $row; } $row['diff'] = $row[$stat] / $min; return $row; }); }); }
php
private function processDiffs(array $tables, Config $config) { $stat = $config['diff_col']; if ($config['compare']) { return $tables; } if (!in_array('diff', $config['cols'])) { return $tables; } if (!in_array($stat, $config['cols'])) { throw new \InvalidArgumentException(sprintf( 'The "%s" column must be visible when using the diff column', $stat )); } return F\map($tables, function ($table) use ($stat) { $means = F\map($table, function ($row) use ($stat) { return $row[$stat]; }); $min = min($means); return F\map($table, function ($row) use ($min, $stat) { if ($row[$stat] === 0) { $row['diff'] = 0; return $row; } $row['diff'] = $row[$stat] / $min; return $row; }); }); }
[ "private", "function", "processDiffs", "(", "array", "$", "tables", ",", "Config", "$", "config", ")", "{", "$", "stat", "=", "$", "config", "[", "'diff_col'", "]", ";", "if", "(", "$", "config", "[", "'compare'", "]", ")", "{", "return", "$", "tables", ";", "}", "if", "(", "!", "in_array", "(", "'diff'", ",", "$", "config", "[", "'cols'", "]", ")", ")", "{", "return", "$", "tables", ";", "}", "if", "(", "!", "in_array", "(", "$", "stat", ",", "$", "config", "[", "'cols'", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The \"%s\" column must be visible when using the diff column'", ",", "$", "stat", ")", ")", ";", "}", "return", "F", "\\", "map", "(", "$", "tables", ",", "function", "(", "$", "table", ")", "use", "(", "$", "stat", ")", "{", "$", "means", "=", "F", "\\", "map", "(", "$", "table", ",", "function", "(", "$", "row", ")", "use", "(", "$", "stat", ")", "{", "return", "$", "row", "[", "$", "stat", "]", ";", "}", ")", ";", "$", "min", "=", "min", "(", "$", "means", ")", ";", "return", "F", "\\", "map", "(", "$", "table", ",", "function", "(", "$", "row", ")", "use", "(", "$", "min", ",", "$", "stat", ")", "{", "if", "(", "$", "row", "[", "$", "stat", "]", "===", "0", ")", "{", "$", "row", "[", "'diff'", "]", "=", "0", ";", "return", "$", "row", ";", "}", "$", "row", "[", "'diff'", "]", "=", "$", "row", "[", "$", "stat", "]", "/", "$", "min", ";", "return", "$", "row", ";", "}", ")", ";", "}", ")", ";", "}" ]
Calculate the ``diff`` column if it is displayed. @param array $tables @param Config $config @return array
[ "Calculate", "the", "diff", "column", "if", "it", "is", "displayed", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/TableGenerator.php#L122-L159
train
phpbench/phpbench
lib/Report/Generator/TableGenerator.php
TableGenerator.processSort
private function processSort(array $table, Config $config) { if ($config['sort']) { $cols = array_reverse($config['sort']); foreach ($cols as $colName => $direction) { Sort::mergeSort($table, function ($elementA, $elementB) use ($colName, $direction) { if ($elementA[$colName] == $elementB[$colName]) { return 0; } if ($direction === 'asc') { return $elementA[$colName] < $elementB[$colName] ? -1 : 1; } return $elementA[$colName] > $elementB[$colName] ? -1 : 1; }); } } if ($config['break']) { foreach ($config['break'] as $colName) { Sort::mergeSort($table, function ($elementA, $elementB) use ($colName) { if ($elementA[$colName] == $elementB[$colName]) { return 0; } return $elementA[$colName] < $elementB[$colName] ? -1 : 1; }); } } return $table; }
php
private function processSort(array $table, Config $config) { if ($config['sort']) { $cols = array_reverse($config['sort']); foreach ($cols as $colName => $direction) { Sort::mergeSort($table, function ($elementA, $elementB) use ($colName, $direction) { if ($elementA[$colName] == $elementB[$colName]) { return 0; } if ($direction === 'asc') { return $elementA[$colName] < $elementB[$colName] ? -1 : 1; } return $elementA[$colName] > $elementB[$colName] ? -1 : 1; }); } } if ($config['break']) { foreach ($config['break'] as $colName) { Sort::mergeSort($table, function ($elementA, $elementB) use ($colName) { if ($elementA[$colName] == $elementB[$colName]) { return 0; } return $elementA[$colName] < $elementB[$colName] ? -1 : 1; }); } } return $table; }
[ "private", "function", "processSort", "(", "array", "$", "table", ",", "Config", "$", "config", ")", "{", "if", "(", "$", "config", "[", "'sort'", "]", ")", "{", "$", "cols", "=", "array_reverse", "(", "$", "config", "[", "'sort'", "]", ")", ";", "foreach", "(", "$", "cols", "as", "$", "colName", "=>", "$", "direction", ")", "{", "Sort", "::", "mergeSort", "(", "$", "table", ",", "function", "(", "$", "elementA", ",", "$", "elementB", ")", "use", "(", "$", "colName", ",", "$", "direction", ")", "{", "if", "(", "$", "elementA", "[", "$", "colName", "]", "==", "$", "elementB", "[", "$", "colName", "]", ")", "{", "return", "0", ";", "}", "if", "(", "$", "direction", "===", "'asc'", ")", "{", "return", "$", "elementA", "[", "$", "colName", "]", "<", "$", "elementB", "[", "$", "colName", "]", "?", "-", "1", ":", "1", ";", "}", "return", "$", "elementA", "[", "$", "colName", "]", ">", "$", "elementB", "[", "$", "colName", "]", "?", "-", "1", ":", "1", ";", "}", ")", ";", "}", "}", "if", "(", "$", "config", "[", "'break'", "]", ")", "{", "foreach", "(", "$", "config", "[", "'break'", "]", "as", "$", "colName", ")", "{", "Sort", "::", "mergeSort", "(", "$", "table", ",", "function", "(", "$", "elementA", ",", "$", "elementB", ")", "use", "(", "$", "colName", ")", "{", "if", "(", "$", "elementA", "[", "$", "colName", "]", "==", "$", "elementB", "[", "$", "colName", "]", ")", "{", "return", "0", ";", "}", "return", "$", "elementA", "[", "$", "colName", "]", "<", "$", "elementB", "[", "$", "colName", "]", "?", "-", "1", ":", "1", ";", "}", ")", ";", "}", "}", "return", "$", "table", ";", "}" ]
Process the sorting, also break sorting. @param array $table @param Config $config @return array
[ "Process", "the", "sorting", "also", "break", "sorting", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/TableGenerator.php#L169-L202
train
phpbench/phpbench
lib/Report/Generator/TableGenerator.php
TableGenerator.processCols
private function processCols(array $tables, Config $config) { if ($config['cols']) { $cols = $config['cols']; if ($config['compare']) { $cols[] = $config['compare']; $cols = array_merge($cols, $config['compare_fields']); } $tables = F\map($tables, function ($table) use ($cols) { return F\map($table, function ($row) use ($cols) { $newRow = $row->newInstance([]); foreach ($cols as $col) { if ($col === 'diff') { continue; } $newRow[$col] = $row[$col]; } return $newRow; }); }); } return $tables; }
php
private function processCols(array $tables, Config $config) { if ($config['cols']) { $cols = $config['cols']; if ($config['compare']) { $cols[] = $config['compare']; $cols = array_merge($cols, $config['compare_fields']); } $tables = F\map($tables, function ($table) use ($cols) { return F\map($table, function ($row) use ($cols) { $newRow = $row->newInstance([]); foreach ($cols as $col) { if ($col === 'diff') { continue; } $newRow[$col] = $row[$col]; } return $newRow; }); }); } return $tables; }
[ "private", "function", "processCols", "(", "array", "$", "tables", ",", "Config", "$", "config", ")", "{", "if", "(", "$", "config", "[", "'cols'", "]", ")", "{", "$", "cols", "=", "$", "config", "[", "'cols'", "]", ";", "if", "(", "$", "config", "[", "'compare'", "]", ")", "{", "$", "cols", "[", "]", "=", "$", "config", "[", "'compare'", "]", ";", "$", "cols", "=", "array_merge", "(", "$", "cols", ",", "$", "config", "[", "'compare_fields'", "]", ")", ";", "}", "$", "tables", "=", "F", "\\", "map", "(", "$", "tables", ",", "function", "(", "$", "table", ")", "use", "(", "$", "cols", ")", "{", "return", "F", "\\", "map", "(", "$", "table", ",", "function", "(", "$", "row", ")", "use", "(", "$", "cols", ")", "{", "$", "newRow", "=", "$", "row", "->", "newInstance", "(", "[", "]", ")", ";", "foreach", "(", "$", "cols", "as", "$", "col", ")", "{", "if", "(", "$", "col", "===", "'diff'", ")", "{", "continue", ";", "}", "$", "newRow", "[", "$", "col", "]", "=", "$", "row", "[", "$", "col", "]", ";", "}", "return", "$", "newRow", ";", "}", ")", ";", "}", ")", ";", "}", "return", "$", "tables", ";", "}" ]
Remove unwanted columns from the tables. @param array $tables @param Config $config @return array
[ "Remove", "unwanted", "columns", "from", "the", "tables", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/TableGenerator.php#L249-L275
train
phpbench/phpbench
lib/Report/Generator/TableGenerator.php
TableGenerator.generateDocument
private function generateDocument(array $tables, Config $config) { $document = new Document(); $reportsEl = $document->createRoot('reports'); $reportsEl->setAttribute('name', 'table'); $reportEl = $reportsEl->appendElement('report'); $classMap = array_merge( $this->classMap, $config['class_map'] ); if (isset($config['title'])) { $reportEl->setAttribute('title', $config['title']); } if (isset($config['description'])) { $reportEl->appendElement('description', $config['description']); } foreach ($tables as $breakHash => $table) { $tableEl = $reportEl->appendElement('table'); // Build the col(umn) definitions. foreach ($table as $row) { $colsEl = $tableEl->appendElement('cols'); foreach ($row->getNames() as $colName) { $colEl = $colsEl->appendElement('col'); $colEl->setAttribute('name', $colName); // column labels are the column names by default. // the user may override by column name or column index. $colLabel = $colName; if (isset($config['labels'][$colName])) { $colLabel = $config['labels'][$colName]; } $colEl->setAttribute('label', $colLabel); } break; } if ($breakHash) { $tableEl->setAttribute('title', $breakHash); } $groupEl = $tableEl->appendElement('group'); $groupEl->setAttribute('name', 'body'); foreach ($table as $row) { $rowEl = $groupEl->appendElement('row'); // apply formatter options foreach ($row->getFormatParams() as $paramName => $paramValue) { $paramEl = $rowEl->appendElement('formatter-param', $paramValue); $paramEl->setAttribute('name', $paramName); } foreach ($row as $key => $value) { $cellEl = $rowEl->appendElement('cell', $value); $cellEl->setAttribute('name', $key); if (isset($classMap[$key])) { $cellEl->setAttribute('class', implode(' ', $classMap[$key])); } } } } return $document; }
php
private function generateDocument(array $tables, Config $config) { $document = new Document(); $reportsEl = $document->createRoot('reports'); $reportsEl->setAttribute('name', 'table'); $reportEl = $reportsEl->appendElement('report'); $classMap = array_merge( $this->classMap, $config['class_map'] ); if (isset($config['title'])) { $reportEl->setAttribute('title', $config['title']); } if (isset($config['description'])) { $reportEl->appendElement('description', $config['description']); } foreach ($tables as $breakHash => $table) { $tableEl = $reportEl->appendElement('table'); // Build the col(umn) definitions. foreach ($table as $row) { $colsEl = $tableEl->appendElement('cols'); foreach ($row->getNames() as $colName) { $colEl = $colsEl->appendElement('col'); $colEl->setAttribute('name', $colName); // column labels are the column names by default. // the user may override by column name or column index. $colLabel = $colName; if (isset($config['labels'][$colName])) { $colLabel = $config['labels'][$colName]; } $colEl->setAttribute('label', $colLabel); } break; } if ($breakHash) { $tableEl->setAttribute('title', $breakHash); } $groupEl = $tableEl->appendElement('group'); $groupEl->setAttribute('name', 'body'); foreach ($table as $row) { $rowEl = $groupEl->appendElement('row'); // apply formatter options foreach ($row->getFormatParams() as $paramName => $paramValue) { $paramEl = $rowEl->appendElement('formatter-param', $paramValue); $paramEl->setAttribute('name', $paramName); } foreach ($row as $key => $value) { $cellEl = $rowEl->appendElement('cell', $value); $cellEl->setAttribute('name', $key); if (isset($classMap[$key])) { $cellEl->setAttribute('class', implode(' ', $classMap[$key])); } } } } return $document; }
[ "private", "function", "generateDocument", "(", "array", "$", "tables", ",", "Config", "$", "config", ")", "{", "$", "document", "=", "new", "Document", "(", ")", ";", "$", "reportsEl", "=", "$", "document", "->", "createRoot", "(", "'reports'", ")", ";", "$", "reportsEl", "->", "setAttribute", "(", "'name'", ",", "'table'", ")", ";", "$", "reportEl", "=", "$", "reportsEl", "->", "appendElement", "(", "'report'", ")", ";", "$", "classMap", "=", "array_merge", "(", "$", "this", "->", "classMap", ",", "$", "config", "[", "'class_map'", "]", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'title'", "]", ")", ")", "{", "$", "reportEl", "->", "setAttribute", "(", "'title'", ",", "$", "config", "[", "'title'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'description'", "]", ")", ")", "{", "$", "reportEl", "->", "appendElement", "(", "'description'", ",", "$", "config", "[", "'description'", "]", ")", ";", "}", "foreach", "(", "$", "tables", "as", "$", "breakHash", "=>", "$", "table", ")", "{", "$", "tableEl", "=", "$", "reportEl", "->", "appendElement", "(", "'table'", ")", ";", "// Build the col(umn) definitions.", "foreach", "(", "$", "table", "as", "$", "row", ")", "{", "$", "colsEl", "=", "$", "tableEl", "->", "appendElement", "(", "'cols'", ")", ";", "foreach", "(", "$", "row", "->", "getNames", "(", ")", "as", "$", "colName", ")", "{", "$", "colEl", "=", "$", "colsEl", "->", "appendElement", "(", "'col'", ")", ";", "$", "colEl", "->", "setAttribute", "(", "'name'", ",", "$", "colName", ")", ";", "// column labels are the column names by default.", "// the user may override by column name or column index.", "$", "colLabel", "=", "$", "colName", ";", "if", "(", "isset", "(", "$", "config", "[", "'labels'", "]", "[", "$", "colName", "]", ")", ")", "{", "$", "colLabel", "=", "$", "config", "[", "'labels'", "]", "[", "$", "colName", "]", ";", "}", "$", "colEl", "->", "setAttribute", "(", "'label'", ",", "$", "colLabel", ")", ";", "}", "break", ";", "}", "if", "(", "$", "breakHash", ")", "{", "$", "tableEl", "->", "setAttribute", "(", "'title'", ",", "$", "breakHash", ")", ";", "}", "$", "groupEl", "=", "$", "tableEl", "->", "appendElement", "(", "'group'", ")", ";", "$", "groupEl", "->", "setAttribute", "(", "'name'", ",", "'body'", ")", ";", "foreach", "(", "$", "table", "as", "$", "row", ")", "{", "$", "rowEl", "=", "$", "groupEl", "->", "appendElement", "(", "'row'", ")", ";", "// apply formatter options", "foreach", "(", "$", "row", "->", "getFormatParams", "(", ")", "as", "$", "paramName", "=>", "$", "paramValue", ")", "{", "$", "paramEl", "=", "$", "rowEl", "->", "appendElement", "(", "'formatter-param'", ",", "$", "paramValue", ")", ";", "$", "paramEl", "->", "setAttribute", "(", "'name'", ",", "$", "paramName", ")", ";", "}", "foreach", "(", "$", "row", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "cellEl", "=", "$", "rowEl", "->", "appendElement", "(", "'cell'", ",", "$", "value", ")", ";", "$", "cellEl", "->", "setAttribute", "(", "'name'", ",", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "classMap", "[", "$", "key", "]", ")", ")", "{", "$", "cellEl", "->", "setAttribute", "(", "'class'", ",", "implode", "(", "' '", ",", "$", "classMap", "[", "$", "key", "]", ")", ")", ";", "}", "}", "}", "}", "return", "$", "document", ";", "}" ]
Generate the report DOM document to pass to the report renderer. @param array $tables @param Config $config @return Document
[ "Generate", "the", "report", "DOM", "document", "to", "pass", "to", "the", "report", "renderer", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/TableGenerator.php#L515-L587
train
phpbench/phpbench
lib/Report/Generator/TableGenerator.php
TableGenerator.resolveCompareColumnName
private function resolveCompareColumnName(Row $row, $name, $index = 1) { if (!isset($row[$name])) { return $name; } $newName = $name . '#' . (string) $index++; if (!isset($row[$newName])) { return $newName; } return $this->resolveCompareColumnName($row, $name, $index); }
php
private function resolveCompareColumnName(Row $row, $name, $index = 1) { if (!isset($row[$name])) { return $name; } $newName = $name . '#' . (string) $index++; if (!isset($row[$newName])) { return $newName; } return $this->resolveCompareColumnName($row, $name, $index); }
[ "private", "function", "resolveCompareColumnName", "(", "Row", "$", "row", ",", "$", "name", ",", "$", "index", "=", "1", ")", "{", "if", "(", "!", "isset", "(", "$", "row", "[", "$", "name", "]", ")", ")", "{", "return", "$", "name", ";", "}", "$", "newName", "=", "$", "name", ".", "'#'", ".", "(", "string", ")", "$", "index", "++", ";", "if", "(", "!", "isset", "(", "$", "row", "[", "$", "newName", "]", ")", ")", "{", "return", "$", "newName", ";", "}", "return", "$", "this", "->", "resolveCompareColumnName", "(", "$", "row", ",", "$", "name", ",", "$", "index", ")", ";", "}" ]
Recursively resolve a comparison column - find a column name that doesn't already exist by adding and incrementing an index. @param Row $row @param int $index @return string
[ "Recursively", "resolve", "a", "comparison", "column", "-", "find", "a", "column", "name", "that", "doesn", "t", "already", "exist", "by", "adding", "and", "incrementing", "an", "index", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Report/Generator/TableGenerator.php#L611-L624
train
phpbench/phpbench
lib/Json/JsonDecoder.php
JsonDecoder.normalize
private function normalize($jsonString) { if (!is_string($jsonString)) { throw new \InvalidArgumentException(sprintf( 'Expected a string, got "%s"', gettype($jsonString) )); } $chars = str_split($jsonString); $inRight = $inQuote = $inFakeQuote = false; $fakeQuoteStart = null; if (empty($chars)) { return; } if ($chars[0] !== '{') { array_unshift($chars, '{'); $chars[] = '}'; } for ($index = 0; $index < count($chars); $index++) { $char = $chars[$index]; $prevChar = isset($chars[$index - 1]) ? $chars[$index - 1] : null; if (!$inQuote && $prevChar == ':') { $inRight = true; } if (!$inQuote && preg_match('{\{,}', $char)) { $inRight = false; } // detect start of unquoted string if (!$inQuote && preg_match('{[\$a-zA-Z0-9]}', $char)) { array_splice($chars, $index, 0, '"'); $fakeQuoteStart = $index; $index++; $inQuote = $inFakeQuote = true; continue; } // if we added a "fake" quote, look for the end of the unquoted string if ($inFakeQuote && preg_match('{[\s:\}\],]}', $char)) { // if we are on the left side, then "]" is OK. if (!$inRight && $char === ']') { continue; } if ($inRight) { // extract the right hand value $string = implode('', array_slice($chars, $fakeQuoteStart + 1, $index - 1 - $fakeQuoteStart)); // if it is a number, then we don't quote it if (is_numeric($string)) { unset($chars[$fakeQuoteStart]); $chars = array_values($chars); $inQuote = $inFakeQuote = false; $index--; continue; } // if it is a boolean, then we don't quote it if (in_array($string, ['true', 'false'])) { unset($chars[$fakeQuoteStart]); $chars = array_values($chars); $inQuote = $inFakeQuote = false; $index--; continue; } } // add the ending quote array_splice($chars, $index, 0, '"'); $index++; $inQuote = $inFakeQuote = false; continue; } // enter standard quote mode if (!$inQuote && $char === '"') { $inQuote = true; continue; } // if we are in quote mode and encounter a closing quote, and the last character // was not the escape character if ($inQuote && $char === '"' && $prevChar !== '\\') { $inQuote = $inFakeQuote = false; continue; } } // if we were in a fake quote and hit the end, then add the closing quote if ($inFakeQuote) { $chars[] = '"'; } $normalized = implode('', $chars); return $normalized; }
php
private function normalize($jsonString) { if (!is_string($jsonString)) { throw new \InvalidArgumentException(sprintf( 'Expected a string, got "%s"', gettype($jsonString) )); } $chars = str_split($jsonString); $inRight = $inQuote = $inFakeQuote = false; $fakeQuoteStart = null; if (empty($chars)) { return; } if ($chars[0] !== '{') { array_unshift($chars, '{'); $chars[] = '}'; } for ($index = 0; $index < count($chars); $index++) { $char = $chars[$index]; $prevChar = isset($chars[$index - 1]) ? $chars[$index - 1] : null; if (!$inQuote && $prevChar == ':') { $inRight = true; } if (!$inQuote && preg_match('{\{,}', $char)) { $inRight = false; } // detect start of unquoted string if (!$inQuote && preg_match('{[\$a-zA-Z0-9]}', $char)) { array_splice($chars, $index, 0, '"'); $fakeQuoteStart = $index; $index++; $inQuote = $inFakeQuote = true; continue; } // if we added a "fake" quote, look for the end of the unquoted string if ($inFakeQuote && preg_match('{[\s:\}\],]}', $char)) { // if we are on the left side, then "]" is OK. if (!$inRight && $char === ']') { continue; } if ($inRight) { // extract the right hand value $string = implode('', array_slice($chars, $fakeQuoteStart + 1, $index - 1 - $fakeQuoteStart)); // if it is a number, then we don't quote it if (is_numeric($string)) { unset($chars[$fakeQuoteStart]); $chars = array_values($chars); $inQuote = $inFakeQuote = false; $index--; continue; } // if it is a boolean, then we don't quote it if (in_array($string, ['true', 'false'])) { unset($chars[$fakeQuoteStart]); $chars = array_values($chars); $inQuote = $inFakeQuote = false; $index--; continue; } } // add the ending quote array_splice($chars, $index, 0, '"'); $index++; $inQuote = $inFakeQuote = false; continue; } // enter standard quote mode if (!$inQuote && $char === '"') { $inQuote = true; continue; } // if we are in quote mode and encounter a closing quote, and the last character // was not the escape character if ($inQuote && $char === '"' && $prevChar !== '\\') { $inQuote = $inFakeQuote = false; continue; } } // if we were in a fake quote and hit the end, then add the closing quote if ($inFakeQuote) { $chars[] = '"'; } $normalized = implode('', $chars); return $normalized; }
[ "private", "function", "normalize", "(", "$", "jsonString", ")", "{", "if", "(", "!", "is_string", "(", "$", "jsonString", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Expected a string, got \"%s\"'", ",", "gettype", "(", "$", "jsonString", ")", ")", ")", ";", "}", "$", "chars", "=", "str_split", "(", "$", "jsonString", ")", ";", "$", "inRight", "=", "$", "inQuote", "=", "$", "inFakeQuote", "=", "false", ";", "$", "fakeQuoteStart", "=", "null", ";", "if", "(", "empty", "(", "$", "chars", ")", ")", "{", "return", ";", "}", "if", "(", "$", "chars", "[", "0", "]", "!==", "'{'", ")", "{", "array_unshift", "(", "$", "chars", ",", "'{'", ")", ";", "$", "chars", "[", "]", "=", "'}'", ";", "}", "for", "(", "$", "index", "=", "0", ";", "$", "index", "<", "count", "(", "$", "chars", ")", ";", "$", "index", "++", ")", "{", "$", "char", "=", "$", "chars", "[", "$", "index", "]", ";", "$", "prevChar", "=", "isset", "(", "$", "chars", "[", "$", "index", "-", "1", "]", ")", "?", "$", "chars", "[", "$", "index", "-", "1", "]", ":", "null", ";", "if", "(", "!", "$", "inQuote", "&&", "$", "prevChar", "==", "':'", ")", "{", "$", "inRight", "=", "true", ";", "}", "if", "(", "!", "$", "inQuote", "&&", "preg_match", "(", "'{\\{,}'", ",", "$", "char", ")", ")", "{", "$", "inRight", "=", "false", ";", "}", "// detect start of unquoted string", "if", "(", "!", "$", "inQuote", "&&", "preg_match", "(", "'{[\\$a-zA-Z0-9]}'", ",", "$", "char", ")", ")", "{", "array_splice", "(", "$", "chars", ",", "$", "index", ",", "0", ",", "'\"'", ")", ";", "$", "fakeQuoteStart", "=", "$", "index", ";", "$", "index", "++", ";", "$", "inQuote", "=", "$", "inFakeQuote", "=", "true", ";", "continue", ";", "}", "// if we added a \"fake\" quote, look for the end of the unquoted string", "if", "(", "$", "inFakeQuote", "&&", "preg_match", "(", "'{[\\s:\\}\\],]}'", ",", "$", "char", ")", ")", "{", "// if we are on the left side, then \"]\" is OK.", "if", "(", "!", "$", "inRight", "&&", "$", "char", "===", "']'", ")", "{", "continue", ";", "}", "if", "(", "$", "inRight", ")", "{", "// extract the right hand value", "$", "string", "=", "implode", "(", "''", ",", "array_slice", "(", "$", "chars", ",", "$", "fakeQuoteStart", "+", "1", ",", "$", "index", "-", "1", "-", "$", "fakeQuoteStart", ")", ")", ";", "// if it is a number, then we don't quote it", "if", "(", "is_numeric", "(", "$", "string", ")", ")", "{", "unset", "(", "$", "chars", "[", "$", "fakeQuoteStart", "]", ")", ";", "$", "chars", "=", "array_values", "(", "$", "chars", ")", ";", "$", "inQuote", "=", "$", "inFakeQuote", "=", "false", ";", "$", "index", "--", ";", "continue", ";", "}", "// if it is a boolean, then we don't quote it", "if", "(", "in_array", "(", "$", "string", ",", "[", "'true'", ",", "'false'", "]", ")", ")", "{", "unset", "(", "$", "chars", "[", "$", "fakeQuoteStart", "]", ")", ";", "$", "chars", "=", "array_values", "(", "$", "chars", ")", ";", "$", "inQuote", "=", "$", "inFakeQuote", "=", "false", ";", "$", "index", "--", ";", "continue", ";", "}", "}", "// add the ending quote", "array_splice", "(", "$", "chars", ",", "$", "index", ",", "0", ",", "'\"'", ")", ";", "$", "index", "++", ";", "$", "inQuote", "=", "$", "inFakeQuote", "=", "false", ";", "continue", ";", "}", "// enter standard quote mode", "if", "(", "!", "$", "inQuote", "&&", "$", "char", "===", "'\"'", ")", "{", "$", "inQuote", "=", "true", ";", "continue", ";", "}", "// if we are in quote mode and encounter a closing quote, and the last character", "// was not the escape character", "if", "(", "$", "inQuote", "&&", "$", "char", "===", "'\"'", "&&", "$", "prevChar", "!==", "'\\\\'", ")", "{", "$", "inQuote", "=", "$", "inFakeQuote", "=", "false", ";", "continue", ";", "}", "}", "// if we were in a fake quote and hit the end, then add the closing quote", "if", "(", "$", "inFakeQuote", ")", "{", "$", "chars", "[", "]", "=", "'\"'", ";", "}", "$", "normalized", "=", "implode", "(", "''", ",", "$", "chars", ")", ";", "return", "$", "normalized", ";", "}" ]
Allow "non-strict" JSON - i.e. if no quotes are provided then try and add them.
[ "Allow", "non", "-", "strict", "JSON", "-", "i", ".", "e", ".", "if", "no", "quotes", "are", "provided", "then", "try", "and", "add", "them", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Json/JsonDecoder.php#L59-L168
train
phpbench/phpbench
lib/Model/Subject.php
Subject.createVariant
public function createVariant(ParameterSet $parameterSet, $revolutions, $warmup, array $computedStats = []) { $variant = new Variant( $this, $parameterSet, $revolutions, $warmup, $computedStats ); $this->variants[] = $variant; return $variant; }
php
public function createVariant(ParameterSet $parameterSet, $revolutions, $warmup, array $computedStats = []) { $variant = new Variant( $this, $parameterSet, $revolutions, $warmup, $computedStats ); $this->variants[] = $variant; return $variant; }
[ "public", "function", "createVariant", "(", "ParameterSet", "$", "parameterSet", ",", "$", "revolutions", ",", "$", "warmup", ",", "array", "$", "computedStats", "=", "[", "]", ")", "{", "$", "variant", "=", "new", "Variant", "(", "$", "this", ",", "$", "parameterSet", ",", "$", "revolutions", ",", "$", "warmup", ",", "$", "computedStats", ")", ";", "$", "this", "->", "variants", "[", "]", "=", "$", "variant", ";", "return", "$", "variant", ";", "}" ]
Create and add a new variant based on this subject. @param ParameterSet $parameterSet @param int $revolutions @param int $warmup @return Variant.
[ "Create", "and", "add", "a", "new", "variant", "based", "on", "this", "subject", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Model/Subject.php#L111-L123
train
ackintosh/ganesha
src/Ganesha/Storage.php
Storage.setFailureCount
public function setFailureCount($service, $failureCount) { $this->adapter->save($this->failureKey($service), $failureCount); }
php
public function setFailureCount($service, $failureCount) { $this->adapter->save($this->failureKey($service), $failureCount); }
[ "public", "function", "setFailureCount", "(", "$", "service", ",", "$", "failureCount", ")", "{", "$", "this", "->", "adapter", "->", "save", "(", "$", "this", "->", "failureKey", "(", "$", "service", ")", ",", "$", "failureCount", ")", ";", "}" ]
sets failure count @param $service @param $failureCount @throws StorageException
[ "sets", "failure", "count" ]
a2058169f8f3630b6545f415445c57ce853aec27
https://github.com/ackintosh/ganesha/blob/a2058169f8f3630b6545f415445c57ce853aec27/src/Ganesha/Storage.php#L202-L205
train
ackintosh/ganesha
src/Ganesha/Storage.php
Storage.setLastFailureTime
public function setLastFailureTime($service, $lastFailureTime) { $this->adapter->saveLastFailureTime($this->lastFailureKey($service), $lastFailureTime); }
php
public function setLastFailureTime($service, $lastFailureTime) { $this->adapter->saveLastFailureTime($this->lastFailureKey($service), $lastFailureTime); }
[ "public", "function", "setLastFailureTime", "(", "$", "service", ",", "$", "lastFailureTime", ")", "{", "$", "this", "->", "adapter", "->", "saveLastFailureTime", "(", "$", "this", "->", "lastFailureKey", "(", "$", "service", ")", ",", "$", "lastFailureTime", ")", ";", "}" ]
sets last failure time @param string $service @param int $lastFailureTime @return void @throws StorageException
[ "sets", "last", "failure", "time" ]
a2058169f8f3630b6545f415445c57ce853aec27
https://github.com/ackintosh/ganesha/blob/a2058169f8f3630b6545f415445c57ce853aec27/src/Ganesha/Storage.php#L215-L218
train
ackintosh/ganesha
src/Ganesha/Storage/Adapter/Memcached.php
Memcached.throwExceptionIfErrorOccurred
private function throwExceptionIfErrorOccurred() { $errorResultCodes = [ \Memcached::RES_FAILURE, \Memcached::RES_SERVER_TEMPORARILY_DISABLED, \Memcached::RES_SERVER_MEMORY_ALLOCATION_FAILURE, ]; if (in_array($this->memcached->getResultCode(), $errorResultCodes, true)) { throw new StorageException($this->memcached->getResultMessage()); } }
php
private function throwExceptionIfErrorOccurred() { $errorResultCodes = [ \Memcached::RES_FAILURE, \Memcached::RES_SERVER_TEMPORARILY_DISABLED, \Memcached::RES_SERVER_MEMORY_ALLOCATION_FAILURE, ]; if (in_array($this->memcached->getResultCode(), $errorResultCodes, true)) { throw new StorageException($this->memcached->getResultMessage()); } }
[ "private", "function", "throwExceptionIfErrorOccurred", "(", ")", "{", "$", "errorResultCodes", "=", "[", "\\", "Memcached", "::", "RES_FAILURE", ",", "\\", "Memcached", "::", "RES_SERVER_TEMPORARILY_DISABLED", ",", "\\", "Memcached", "::", "RES_SERVER_MEMORY_ALLOCATION_FAILURE", ",", "]", ";", "if", "(", "in_array", "(", "$", "this", "->", "memcached", "->", "getResultCode", "(", ")", ",", "$", "errorResultCodes", ",", "true", ")", ")", "{", "throw", "new", "StorageException", "(", "$", "this", "->", "memcached", "->", "getResultMessage", "(", ")", ")", ";", "}", "}" ]
Throws an exception if some error occurs in memcached. @return void @throws StorageException
[ "Throws", "an", "exception", "if", "some", "error", "occurs", "in", "memcached", "." ]
a2058169f8f3630b6545f415445c57ce853aec27
https://github.com/ackintosh/ganesha/blob/a2058169f8f3630b6545f415445c57ce853aec27/src/Ganesha/Storage/Adapter/Memcached.php#L199-L210
train
VKCOM/vk-php-sdk
src/VK/OAuth/VKOAuth.php
VKOAuth.getAuthorizeUrl
public function getAuthorizeUrl(string $response_type, int $client_id, string $redirect_uri, string $display, ?array $scope = null, ?string $state = null, ?array $group_ids = null, bool $revoke = false): string { $scope_mask = 0; foreach ($scope as $scope_setting) { $scope_mask |= $scope_setting; } $params = array( static::PARAM_CLIENT_ID => $client_id, static::PARAM_REDIRECT_URI => $redirect_uri, static::PARAM_DISPLAY => $display, static::PARAM_SCOPE => $scope_mask, static::PARAM_STATE => $state, static::PARAM_RESPONSE_TYPE => $response_type, static::PARAM_VERSION => $this->version, ); if ($group_ids) { $params[static::PARAM_GROUP_IDS] = implode(',', $group_ids); } if ($revoke) { $params[static::PARAM_REVOKE] = 1; } return $this->host . static::ENDPOINT_AUTHORIZE . '?' . http_build_query($params); }
php
public function getAuthorizeUrl(string $response_type, int $client_id, string $redirect_uri, string $display, ?array $scope = null, ?string $state = null, ?array $group_ids = null, bool $revoke = false): string { $scope_mask = 0; foreach ($scope as $scope_setting) { $scope_mask |= $scope_setting; } $params = array( static::PARAM_CLIENT_ID => $client_id, static::PARAM_REDIRECT_URI => $redirect_uri, static::PARAM_DISPLAY => $display, static::PARAM_SCOPE => $scope_mask, static::PARAM_STATE => $state, static::PARAM_RESPONSE_TYPE => $response_type, static::PARAM_VERSION => $this->version, ); if ($group_ids) { $params[static::PARAM_GROUP_IDS] = implode(',', $group_ids); } if ($revoke) { $params[static::PARAM_REVOKE] = 1; } return $this->host . static::ENDPOINT_AUTHORIZE . '?' . http_build_query($params); }
[ "public", "function", "getAuthorizeUrl", "(", "string", "$", "response_type", ",", "int", "$", "client_id", ",", "string", "$", "redirect_uri", ",", "string", "$", "display", ",", "?", "array", "$", "scope", "=", "null", ",", "?", "string", "$", "state", "=", "null", ",", "?", "array", "$", "group_ids", "=", "null", ",", "bool", "$", "revoke", "=", "false", ")", ":", "string", "{", "$", "scope_mask", "=", "0", ";", "foreach", "(", "$", "scope", "as", "$", "scope_setting", ")", "{", "$", "scope_mask", "|=", "$", "scope_setting", ";", "}", "$", "params", "=", "array", "(", "static", "::", "PARAM_CLIENT_ID", "=>", "$", "client_id", ",", "static", "::", "PARAM_REDIRECT_URI", "=>", "$", "redirect_uri", ",", "static", "::", "PARAM_DISPLAY", "=>", "$", "display", ",", "static", "::", "PARAM_SCOPE", "=>", "$", "scope_mask", ",", "static", "::", "PARAM_STATE", "=>", "$", "state", ",", "static", "::", "PARAM_RESPONSE_TYPE", "=>", "$", "response_type", ",", "static", "::", "PARAM_VERSION", "=>", "$", "this", "->", "version", ",", ")", ";", "if", "(", "$", "group_ids", ")", "{", "$", "params", "[", "static", "::", "PARAM_GROUP_IDS", "]", "=", "implode", "(", "','", ",", "$", "group_ids", ")", ";", "}", "if", "(", "$", "revoke", ")", "{", "$", "params", "[", "static", "::", "PARAM_REVOKE", "]", "=", "1", ";", "}", "return", "$", "this", "->", "host", ".", "static", "::", "ENDPOINT_AUTHORIZE", ".", "'?'", ".", "http_build_query", "(", "$", "params", ")", ";", "}" ]
Get authorize url @param string $response_type @param int $client_id @param string $redirect_uri @param string $display @param int[] $scope @param string $state @param int[] $group_ids @param bool $revoke @return string @see VKOAuthResponseType @see VKOAuthDisplay @see VKOAuthGroupScope @see VKOAuthUserScope
[ "Get", "authorize", "url" ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/OAuth/VKOAuth.php#L79-L105
train
VKCOM/vk-php-sdk
src/VK/OAuth/VKOAuth.php
VKOAuth.checkOAuthResponse
protected function checkOAuthResponse(TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::RESPONSE_KEY_ERROR])) { throw new VKOAuthException("{$decode_body[static::RESPONSE_KEY_ERROR_DESCRIPTION]}. OAuth error {$decode_body[static::RESPONSE_KEY_ERROR]}"); } return $decode_body; }
php
protected function checkOAuthResponse(TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::RESPONSE_KEY_ERROR])) { throw new VKOAuthException("{$decode_body[static::RESPONSE_KEY_ERROR_DESCRIPTION]}. OAuth error {$decode_body[static::RESPONSE_KEY_ERROR]}"); } return $decode_body; }
[ "protected", "function", "checkOAuthResponse", "(", "TransportClientResponse", "$", "response", ")", "{", "$", "this", "->", "checkHttpStatus", "(", "$", "response", ")", ";", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "$", "decode_body", "=", "$", "this", "->", "decodeBody", "(", "$", "body", ")", ";", "if", "(", "isset", "(", "$", "decode_body", "[", "static", "::", "RESPONSE_KEY_ERROR", "]", ")", ")", "{", "throw", "new", "VKOAuthException", "(", "\"{$decode_body[static::RESPONSE_KEY_ERROR_DESCRIPTION]}. OAuth error {$decode_body[static::RESPONSE_KEY_ERROR]}\"", ")", ";", "}", "return", "$", "decode_body", ";", "}" ]
Decodes the authorization response and checks its status code and whether it has an error. @param TransportClientResponse $response @return mixed @throws VKClientException @throws VKOAuthException
[ "Decodes", "the", "authorization", "response", "and", "checks", "its", "status", "code", "and", "whether", "it", "has", "an", "error", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/OAuth/VKOAuth.php#L143-L154
train
VKCOM/vk-php-sdk
src/VK/OAuth/VKOAuth.php
VKOAuth.decodeBody
protected function decodeBody(string $body) { $decoded_body = json_decode($body, true); if ($decoded_body === null || !is_array($decoded_body)) { $decoded_body = []; } return $decoded_body; }
php
protected function decodeBody(string $body) { $decoded_body = json_decode($body, true); if ($decoded_body === null || !is_array($decoded_body)) { $decoded_body = []; } return $decoded_body; }
[ "protected", "function", "decodeBody", "(", "string", "$", "body", ")", "{", "$", "decoded_body", "=", "json_decode", "(", "$", "body", ",", "true", ")", ";", "if", "(", "$", "decoded_body", "===", "null", "||", "!", "is_array", "(", "$", "decoded_body", ")", ")", "{", "$", "decoded_body", "=", "[", "]", ";", "}", "return", "$", "decoded_body", ";", "}" ]
Decodes body. @param string $body @return mixed
[ "Decodes", "body", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/OAuth/VKOAuth.php#L163-L171
train
VKCOM/vk-php-sdk
src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php
VKCallbackApiLongPollExecutor.listen
public function listen(?int $ts = null) { if ($this->server === null) { $this->server = $this->getLongPollServer(); } if ($this->last_ts === null) { $this->last_ts = $this->server[static::SERVER_TIMESTAMP]; } if ($ts === null) { $ts = $this->last_ts; } try { $response = $this->getEvents($this->server[static::SERVER_URL], $this->server[static::SERVER_KEY], $ts); foreach ($response[static::EVENTS_UPDATES] as $event) { $this->handler->parseObject($this->group_id, null, $event[static::EVENT_TYPE], $event[static::EVENT_OBJECT]); } $this->last_ts = $response[static::EVENTS_TS]; } catch (VKLongPollServerKeyExpiredException $e) { $this->server = $this->getLongPollServer(); } return $this->last_ts; }
php
public function listen(?int $ts = null) { if ($this->server === null) { $this->server = $this->getLongPollServer(); } if ($this->last_ts === null) { $this->last_ts = $this->server[static::SERVER_TIMESTAMP]; } if ($ts === null) { $ts = $this->last_ts; } try { $response = $this->getEvents($this->server[static::SERVER_URL], $this->server[static::SERVER_KEY], $ts); foreach ($response[static::EVENTS_UPDATES] as $event) { $this->handler->parseObject($this->group_id, null, $event[static::EVENT_TYPE], $event[static::EVENT_OBJECT]); } $this->last_ts = $response[static::EVENTS_TS]; } catch (VKLongPollServerKeyExpiredException $e) { $this->server = $this->getLongPollServer(); } return $this->last_ts; }
[ "public", "function", "listen", "(", "?", "int", "$", "ts", "=", "null", ")", "{", "if", "(", "$", "this", "->", "server", "===", "null", ")", "{", "$", "this", "->", "server", "=", "$", "this", "->", "getLongPollServer", "(", ")", ";", "}", "if", "(", "$", "this", "->", "last_ts", "===", "null", ")", "{", "$", "this", "->", "last_ts", "=", "$", "this", "->", "server", "[", "static", "::", "SERVER_TIMESTAMP", "]", ";", "}", "if", "(", "$", "ts", "===", "null", ")", "{", "$", "ts", "=", "$", "this", "->", "last_ts", ";", "}", "try", "{", "$", "response", "=", "$", "this", "->", "getEvents", "(", "$", "this", "->", "server", "[", "static", "::", "SERVER_URL", "]", ",", "$", "this", "->", "server", "[", "static", "::", "SERVER_KEY", "]", ",", "$", "ts", ")", ";", "foreach", "(", "$", "response", "[", "static", "::", "EVENTS_UPDATES", "]", "as", "$", "event", ")", "{", "$", "this", "->", "handler", "->", "parseObject", "(", "$", "this", "->", "group_id", ",", "null", ",", "$", "event", "[", "static", "::", "EVENT_TYPE", "]", ",", "$", "event", "[", "static", "::", "EVENT_OBJECT", "]", ")", ";", "}", "$", "this", "->", "last_ts", "=", "$", "response", "[", "static", "::", "EVENTS_TS", "]", ";", "}", "catch", "(", "VKLongPollServerKeyExpiredException", "$", "e", ")", "{", "$", "this", "->", "server", "=", "$", "this", "->", "getLongPollServer", "(", ")", ";", "}", "return", "$", "this", "->", "last_ts", ";", "}" ]
Starts listening to LongPoll events. @param int|null $ts @return null @throws VKLongPollServerTsException @throws VKApiException @throws VKClientException
[ "Starts", "listening", "to", "LongPoll", "events", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php#L79-L104
train
VKCOM/vk-php-sdk
src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php
VKCallbackApiLongPollExecutor.getLongPollServer
protected function getLongPollServer() { $params = array( static::PARAM_GROUP_ID => $this->group_id ); $server = $this->api_client->groups()->getLongPollServer($this->access_token, $params); return array( static::SERVER_URL => $server['server'], static::SERVER_TIMESTAMP => $server['ts'], static::SERVER_KEY => $server['key'], ); }
php
protected function getLongPollServer() { $params = array( static::PARAM_GROUP_ID => $this->group_id ); $server = $this->api_client->groups()->getLongPollServer($this->access_token, $params); return array( static::SERVER_URL => $server['server'], static::SERVER_TIMESTAMP => $server['ts'], static::SERVER_KEY => $server['key'], ); }
[ "protected", "function", "getLongPollServer", "(", ")", "{", "$", "params", "=", "array", "(", "static", "::", "PARAM_GROUP_ID", "=>", "$", "this", "->", "group_id", ")", ";", "$", "server", "=", "$", "this", "->", "api_client", "->", "groups", "(", ")", "->", "getLongPollServer", "(", "$", "this", "->", "access_token", ",", "$", "params", ")", ";", "return", "array", "(", "static", "::", "SERVER_URL", "=>", "$", "server", "[", "'server'", "]", ",", "static", "::", "SERVER_TIMESTAMP", "=>", "$", "server", "[", "'ts'", "]", ",", "static", "::", "SERVER_KEY", "=>", "$", "server", "[", "'key'", "]", ",", ")", ";", "}" ]
Get long poll server @return array @throws VKApiException @throws VKClientException
[ "Get", "long", "poll", "server" ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php#L113-L125
train
VKCOM/vk-php-sdk
src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php
VKCallbackApiLongPollExecutor.getEvents
public function getEvents(string $host, string $key, int $ts) { $params = array( static::PARAM_KEY => $key, static::PARAM_TS => $ts, static::PARAM_WAIT => $this->wait, static::PARAM_ACT => static::VALUE_ACT ); try { $response = $this->http_client->get($host, $params); } catch (TransportRequestException $e) { throw new VKClientException($e); } return $this->parseResponse($params, $response); }
php
public function getEvents(string $host, string $key, int $ts) { $params = array( static::PARAM_KEY => $key, static::PARAM_TS => $ts, static::PARAM_WAIT => $this->wait, static::PARAM_ACT => static::VALUE_ACT ); try { $response = $this->http_client->get($host, $params); } catch (TransportRequestException $e) { throw new VKClientException($e); } return $this->parseResponse($params, $response); }
[ "public", "function", "getEvents", "(", "string", "$", "host", ",", "string", "$", "key", ",", "int", "$", "ts", ")", "{", "$", "params", "=", "array", "(", "static", "::", "PARAM_KEY", "=>", "$", "key", ",", "static", "::", "PARAM_TS", "=>", "$", "ts", ",", "static", "::", "PARAM_WAIT", "=>", "$", "this", "->", "wait", ",", "static", "::", "PARAM_ACT", "=>", "static", "::", "VALUE_ACT", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "http_client", "->", "get", "(", "$", "host", ",", "$", "params", ")", ";", "}", "catch", "(", "TransportRequestException", "$", "e", ")", "{", "throw", "new", "VKClientException", "(", "$", "e", ")", ";", "}", "return", "$", "this", "->", "parseResponse", "(", "$", "params", ",", "$", "response", ")", ";", "}" ]
Retrieves events from long poll server starting from the specified timestamp. @param string $host @param string $key @param int $ts @return mixed @throws VKLongPollServerKeyExpiredException @throws VKLongPollServerTsException @throws VKClientException
[ "Retrieves", "events", "from", "long", "poll", "server", "starting", "from", "the", "specified", "timestamp", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php#L138-L153
train
VKCOM/vk-php-sdk
src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php
VKCallbackApiLongPollExecutor.parseResponse
private function parseResponse(array $params, TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::EVENTS_FAILED])) { switch ($decode_body[static::EVENTS_FAILED]) { case static::ERROR_CODE_INCORRECT_TS_VALUE: $ts = $params[static::PARAM_TS]; $msg = '\'ts\' value is incorrect, minimal value is 1, maximal value is ' . $ts; throw new VKLongPollServerTsException($msg); case static::ERROR_CODE_TOKEN_EXPIRED: throw new VKLongPollServerKeyExpiredException('Try to generate a new key.'); default: throw new VKClientException('Unknown LongPollServer exception, something went wrong. ' . $decode_body); } } return $decode_body; }
php
private function parseResponse(array $params, TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::EVENTS_FAILED])) { switch ($decode_body[static::EVENTS_FAILED]) { case static::ERROR_CODE_INCORRECT_TS_VALUE: $ts = $params[static::PARAM_TS]; $msg = '\'ts\' value is incorrect, minimal value is 1, maximal value is ' . $ts; throw new VKLongPollServerTsException($msg); case static::ERROR_CODE_TOKEN_EXPIRED: throw new VKLongPollServerKeyExpiredException('Try to generate a new key.'); default: throw new VKClientException('Unknown LongPollServer exception, something went wrong. ' . $decode_body); } } return $decode_body; }
[ "private", "function", "parseResponse", "(", "array", "$", "params", ",", "TransportClientResponse", "$", "response", ")", "{", "$", "this", "->", "checkHttpStatus", "(", "$", "response", ")", ";", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "$", "decode_body", "=", "$", "this", "->", "decodeBody", "(", "$", "body", ")", ";", "if", "(", "isset", "(", "$", "decode_body", "[", "static", "::", "EVENTS_FAILED", "]", ")", ")", "{", "switch", "(", "$", "decode_body", "[", "static", "::", "EVENTS_FAILED", "]", ")", "{", "case", "static", "::", "ERROR_CODE_INCORRECT_TS_VALUE", ":", "$", "ts", "=", "$", "params", "[", "static", "::", "PARAM_TS", "]", ";", "$", "msg", "=", "'\\'ts\\' value is incorrect, minimal value is 1, maximal value is '", ".", "$", "ts", ";", "throw", "new", "VKLongPollServerTsException", "(", "$", "msg", ")", ";", "case", "static", "::", "ERROR_CODE_TOKEN_EXPIRED", ":", "throw", "new", "VKLongPollServerKeyExpiredException", "(", "'Try to generate a new key.'", ")", ";", "default", ":", "throw", "new", "VKClientException", "(", "'Unknown LongPollServer exception, something went wrong. '", ".", "$", "decode_body", ")", ";", "}", "}", "return", "$", "decode_body", ";", "}" ]
Decodes the LongPoll response and checks its status code and whether it has a failed key. @param array $params @param TransportClientResponse $response @return mixed @throws VKLongPollServerTsException @throws VKLongPollServerKeyExpiredException @throws VKClientException
[ "Decodes", "the", "LongPoll", "response", "and", "checks", "its", "status", "code", "and", "whether", "it", "has", "a", "failed", "key", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/CallbackApi/LongPoll/VKCallbackApiLongPollExecutor.php#L165-L187
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.get
public function get(string $url, ?array $payload = null): TransportClientResponse { return $this->sendRequest($url . static::QUESTION_MARK . http_build_query($payload), array()); }
php
public function get(string $url, ?array $payload = null): TransportClientResponse { return $this->sendRequest($url . static::QUESTION_MARK . http_build_query($payload), array()); }
[ "public", "function", "get", "(", "string", "$", "url", ",", "?", "array", "$", "payload", "=", "null", ")", ":", "TransportClientResponse", "{", "return", "$", "this", "->", "sendRequest", "(", "$", "url", ".", "static", "::", "QUESTION_MARK", ".", "http_build_query", "(", "$", "payload", ")", ",", "array", "(", ")", ")", ";", "}" ]
Makes get request. @param string $url @param array|null $payload @return TransportClientResponse @throws TransportRequestException
[ "Makes", "get", "request", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L56-L58
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.upload
public function upload(string $url, string $parameter_name, string $path): TransportClientResponse { $payload = array(); $payload[$parameter_name] = (class_exists('CURLFile', false)) ? new \CURLFile($path) : '@' . $path; return $this->sendRequest($url, array( CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array( static::HEADER_UPLOAD_CONTENT_TYPE, ), CURLOPT_POSTFIELDS => $payload )); }
php
public function upload(string $url, string $parameter_name, string $path): TransportClientResponse { $payload = array(); $payload[$parameter_name] = (class_exists('CURLFile', false)) ? new \CURLFile($path) : '@' . $path; return $this->sendRequest($url, array( CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array( static::HEADER_UPLOAD_CONTENT_TYPE, ), CURLOPT_POSTFIELDS => $payload )); }
[ "public", "function", "upload", "(", "string", "$", "url", ",", "string", "$", "parameter_name", ",", "string", "$", "path", ")", ":", "TransportClientResponse", "{", "$", "payload", "=", "array", "(", ")", ";", "$", "payload", "[", "$", "parameter_name", "]", "=", "(", "class_exists", "(", "'CURLFile'", ",", "false", ")", ")", "?", "new", "\\", "CURLFile", "(", "$", "path", ")", ":", "'@'", ".", "$", "path", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "url", ",", "array", "(", "CURLOPT_POST", "=>", "1", ",", "CURLOPT_HTTPHEADER", "=>", "array", "(", "static", "::", "HEADER_UPLOAD_CONTENT_TYPE", ",", ")", ",", "CURLOPT_POSTFIELDS", "=>", "$", "payload", ")", ")", ";", "}" ]
Makes upload request. @param string $url @param string $parameter_name @param string $path @return TransportClientResponse @throws TransportRequestException
[ "Makes", "upload", "request", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L70-L82
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.sendRequest
public function sendRequest(string $url, array $opts) { $curl = curl_init($url); curl_setopt_array($curl, $this->initial_opts + $opts); $response = curl_exec($curl); $curl_error_code = curl_errno($curl); $curl_error = curl_error($curl); $http_status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); curl_close($curl); if ($curl_error || $curl_error_code) { $error_msg = "Failed curl request. Curl error {$curl_error_code}"; if ($curl_error) { $error_msg .= ": {$curl_error}"; } $error_msg .= '.'; throw new TransportRequestException($error_msg); } return $this->parseRawResponse($http_status, $response); }
php
public function sendRequest(string $url, array $opts) { $curl = curl_init($url); curl_setopt_array($curl, $this->initial_opts + $opts); $response = curl_exec($curl); $curl_error_code = curl_errno($curl); $curl_error = curl_error($curl); $http_status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); curl_close($curl); if ($curl_error || $curl_error_code) { $error_msg = "Failed curl request. Curl error {$curl_error_code}"; if ($curl_error) { $error_msg .= ": {$curl_error}"; } $error_msg .= '.'; throw new TransportRequestException($error_msg); } return $this->parseRawResponse($http_status, $response); }
[ "public", "function", "sendRequest", "(", "string", "$", "url", ",", "array", "$", "opts", ")", "{", "$", "curl", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt_array", "(", "$", "curl", ",", "$", "this", "->", "initial_opts", "+", "$", "opts", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "curl", ")", ";", "$", "curl_error_code", "=", "curl_errno", "(", "$", "curl", ")", ";", "$", "curl_error", "=", "curl_error", "(", "$", "curl", ")", ";", "$", "http_status", "=", "curl_getinfo", "(", "$", "curl", ",", "CURLINFO_RESPONSE_CODE", ")", ";", "curl_close", "(", "$", "curl", ")", ";", "if", "(", "$", "curl_error", "||", "$", "curl_error_code", ")", "{", "$", "error_msg", "=", "\"Failed curl request. Curl error {$curl_error_code}\"", ";", "if", "(", "$", "curl_error", ")", "{", "$", "error_msg", ".=", "\": {$curl_error}\"", ";", "}", "$", "error_msg", ".=", "'.'", ";", "throw", "new", "TransportRequestException", "(", "$", "error_msg", ")", ";", "}", "return", "$", "this", "->", "parseRawResponse", "(", "$", "http_status", ",", "$", "response", ")", ";", "}" ]
Makes and sends request. @param string $url @param array $opts @return TransportClientResponse @throws TransportRequestException
[ "Makes", "and", "sends", "request", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L93-L118
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.parseRawResponse
protected function parseRawResponse(int $http_status, string $response) { list($raw_headers, $body) = $this->extractResponseHeadersAndBody($response); $headers = $this->getHeaders($raw_headers); return new TransportClientResponse($http_status, $headers, $body); }
php
protected function parseRawResponse(int $http_status, string $response) { list($raw_headers, $body) = $this->extractResponseHeadersAndBody($response); $headers = $this->getHeaders($raw_headers); return new TransportClientResponse($http_status, $headers, $body); }
[ "protected", "function", "parseRawResponse", "(", "int", "$", "http_status", ",", "string", "$", "response", ")", "{", "list", "(", "$", "raw_headers", ",", "$", "body", ")", "=", "$", "this", "->", "extractResponseHeadersAndBody", "(", "$", "response", ")", ";", "$", "headers", "=", "$", "this", "->", "getHeaders", "(", "$", "raw_headers", ")", ";", "return", "new", "TransportClientResponse", "(", "$", "http_status", ",", "$", "headers", ",", "$", "body", ")", ";", "}" ]
Breaks the raw response down into its headers, body and http status code. @param int $http_status @param string $response @return TransportClientResponse
[ "Breaks", "the", "raw", "response", "down", "into", "its", "headers", "body", "and", "http", "status", "code", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L128-L132
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.extractResponseHeadersAndBody
protected function extractResponseHeadersAndBody(string $response) { $parts = explode("\r\n\r\n", $response); $raw_body = array_pop($parts); $raw_headers = implode("\r\n\r\n", $parts); return [trim($raw_headers), trim($raw_body)]; }
php
protected function extractResponseHeadersAndBody(string $response) { $parts = explode("\r\n\r\n", $response); $raw_body = array_pop($parts); $raw_headers = implode("\r\n\r\n", $parts); return [trim($raw_headers), trim($raw_body)]; }
[ "protected", "function", "extractResponseHeadersAndBody", "(", "string", "$", "response", ")", "{", "$", "parts", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "response", ")", ";", "$", "raw_body", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "raw_headers", "=", "implode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "parts", ")", ";", "return", "[", "trim", "(", "$", "raw_headers", ")", ",", "trim", "(", "$", "raw_body", ")", "]", ";", "}" ]
Extracts the headers and the body into a two-part array. @param string $response @return array
[ "Extracts", "the", "headers", "and", "the", "body", "into", "a", "two", "-", "part", "array", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L141-L147
train
VKCOM/vk-php-sdk
src/VK/TransportClient/Curl/CurlHttpClient.php
CurlHttpClient.getHeaders
protected function getHeaders(string $raw_headers) { // Normalize line breaks $raw_headers = str_replace("\r\n", "\n", $raw_headers); // There will be multiple headers if a 301 was followed // or a proxy was followed, etc $header_collection = explode("\n\n", trim($raw_headers)); // We just want the last response (at the end) $raw_header = array_pop($header_collection); $header_components = explode("\n", $raw_header); $result = array(); $http_status = 0; foreach ($header_components as $line) { if (strpos($line, ': ') === false) { $http_status = $this->getHttpStatus($line); } else { list($key, $value) = explode(': ', $line, 2); $result[$key] = $value; } } return array($http_status, $result); }
php
protected function getHeaders(string $raw_headers) { // Normalize line breaks $raw_headers = str_replace("\r\n", "\n", $raw_headers); // There will be multiple headers if a 301 was followed // or a proxy was followed, etc $header_collection = explode("\n\n", trim($raw_headers)); // We just want the last response (at the end) $raw_header = array_pop($header_collection); $header_components = explode("\n", $raw_header); $result = array(); $http_status = 0; foreach ($header_components as $line) { if (strpos($line, ': ') === false) { $http_status = $this->getHttpStatus($line); } else { list($key, $value) = explode(': ', $line, 2); $result[$key] = $value; } } return array($http_status, $result); }
[ "protected", "function", "getHeaders", "(", "string", "$", "raw_headers", ")", "{", "// Normalize line breaks", "$", "raw_headers", "=", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "raw_headers", ")", ";", "// There will be multiple headers if a 301 was followed", "// or a proxy was followed, etc", "$", "header_collection", "=", "explode", "(", "\"\\n\\n\"", ",", "trim", "(", "$", "raw_headers", ")", ")", ";", "// We just want the last response (at the end)", "$", "raw_header", "=", "array_pop", "(", "$", "header_collection", ")", ";", "$", "header_components", "=", "explode", "(", "\"\\n\"", ",", "$", "raw_header", ")", ";", "$", "result", "=", "array", "(", ")", ";", "$", "http_status", "=", "0", ";", "foreach", "(", "$", "header_components", "as", "$", "line", ")", "{", "if", "(", "strpos", "(", "$", "line", ",", "': '", ")", "===", "false", ")", "{", "$", "http_status", "=", "$", "this", "->", "getHttpStatus", "(", "$", "line", ")", ";", "}", "else", "{", "list", "(", "$", "key", ",", "$", "value", ")", "=", "explode", "(", "': '", ",", "$", "line", ",", "2", ")", ";", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "array", "(", "$", "http_status", ",", "$", "result", ")", ";", "}" ]
Parses the raw headers and sets as an array. @param string The raw headers from the response. @return array
[ "Parses", "the", "raw", "headers", "and", "sets", "as", "an", "array", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/TransportClient/Curl/CurlHttpClient.php#L156-L179
train
VKCOM/vk-php-sdk
src/VK/Client/VKApiRequest.php
VKApiRequest.upload
public function upload(string $upload_url, string $parameter_name, string $path) { try { $response = $this->http_client->upload($upload_url, $parameter_name, $path); } catch (TransportRequestException $e) { throw new VKClientException($e); } return $this->parseResponse($response); }
php
public function upload(string $upload_url, string $parameter_name, string $path) { try { $response = $this->http_client->upload($upload_url, $parameter_name, $path); } catch (TransportRequestException $e) { throw new VKClientException($e); } return $this->parseResponse($response); }
[ "public", "function", "upload", "(", "string", "$", "upload_url", ",", "string", "$", "parameter_name", ",", "string", "$", "path", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "http_client", "->", "upload", "(", "$", "upload_url", ",", "$", "parameter_name", ",", "$", "path", ")", ";", "}", "catch", "(", "TransportRequestException", "$", "e", ")", "{", "throw", "new", "VKClientException", "(", "$", "e", ")", ";", "}", "return", "$", "this", "->", "parseResponse", "(", "$", "response", ")", ";", "}" ]
Uploads data by its path to the given url. @param string $upload_url @param string $parameter_name @param string $path @return mixed @throws VKClientException @throws VKApiException
[ "Uploads", "data", "by", "its", "path", "to", "the", "given", "url", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/Client/VKApiRequest.php#L103-L111
train
VKCOM/vk-php-sdk
src/VK/Client/VKApiRequest.php
VKApiRequest.parseResponse
private function parseResponse(TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::KEY_ERROR])) { $error = $decode_body[static::KEY_ERROR]; $api_error = new VKApiError($error); throw ExceptionMapper::parse($api_error); } if (isset($decode_body[static::KEY_RESPONSE])) { return $decode_body[static::KEY_RESPONSE]; } else { return $decode_body; } }
php
private function parseResponse(TransportClientResponse $response) { $this->checkHttpStatus($response); $body = $response->getBody(); $decode_body = $this->decodeBody($body); if (isset($decode_body[static::KEY_ERROR])) { $error = $decode_body[static::KEY_ERROR]; $api_error = new VKApiError($error); throw ExceptionMapper::parse($api_error); } if (isset($decode_body[static::KEY_RESPONSE])) { return $decode_body[static::KEY_RESPONSE]; } else { return $decode_body; } }
[ "private", "function", "parseResponse", "(", "TransportClientResponse", "$", "response", ")", "{", "$", "this", "->", "checkHttpStatus", "(", "$", "response", ")", ";", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "$", "decode_body", "=", "$", "this", "->", "decodeBody", "(", "$", "body", ")", ";", "if", "(", "isset", "(", "$", "decode_body", "[", "static", "::", "KEY_ERROR", "]", ")", ")", "{", "$", "error", "=", "$", "decode_body", "[", "static", "::", "KEY_ERROR", "]", ";", "$", "api_error", "=", "new", "VKApiError", "(", "$", "error", ")", ";", "throw", "ExceptionMapper", "::", "parse", "(", "$", "api_error", ")", ";", "}", "if", "(", "isset", "(", "$", "decode_body", "[", "static", "::", "KEY_RESPONSE", "]", ")", ")", "{", "return", "$", "decode_body", "[", "static", "::", "KEY_RESPONSE", "]", ";", "}", "else", "{", "return", "$", "decode_body", ";", "}", "}" ]
Decodes the response and checks its status code and whether it has an Api error. Returns decoded response. @param TransportClientResponse $response @return mixed @throws VKApiException @throws VKClientException
[ "Decodes", "the", "response", "and", "checks", "its", "status", "code", "and", "whether", "it", "has", "an", "Api", "error", ".", "Returns", "decoded", "response", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/Client/VKApiRequest.php#L123-L140
train
VKCOM/vk-php-sdk
src/VK/Client/VKApiRequest.php
VKApiRequest.formatParams
private function formatParams(array $params) { foreach ($params as $key => $value) { if (is_array($value)) { $params[$key] = implode(',', $value); } else if (is_bool($value)) { $params[$key] = $value ? 1 : 0; } } return $params; }
php
private function formatParams(array $params) { foreach ($params as $key => $value) { if (is_array($value)) { $params[$key] = implode(',', $value); } else if (is_bool($value)) { $params[$key] = $value ? 1 : 0; } } return $params; }
[ "private", "function", "formatParams", "(", "array", "$", "params", ")", "{", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "params", "[", "$", "key", "]", "=", "implode", "(", "','", ",", "$", "value", ")", ";", "}", "else", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "$", "params", "[", "$", "key", "]", "=", "$", "value", "?", "1", ":", "0", ";", "}", "}", "return", "$", "params", ";", "}" ]
Formats given array of parameters for making the request. @param array $params @return array
[ "Formats", "given", "array", "of", "parameters", "for", "making", "the", "request", "." ]
fff478dfe7d7b1138fdc655a4288bfd35d062a2d
https://github.com/VKCOM/vk-php-sdk/blob/fff478dfe7d7b1138fdc655a4288bfd35d062a2d/src/VK/Client/VKApiRequest.php#L149-L158
train
giansalex/greenter
src/Greenter/Factory/FeFactory.php
FeFactory.send
public function send(DocumentInterface $document) { $xml = $this->getXmlSigned($document); return $this->sender->send($document->getName(), $xml); }
php
public function send(DocumentInterface $document) { $xml = $this->getXmlSigned($document); return $this->sender->send($document->getName(), $xml); }
[ "public", "function", "send", "(", "DocumentInterface", "$", "document", ")", "{", "$", "xml", "=", "$", "this", "->", "getXmlSigned", "(", "$", "document", ")", ";", "return", "$", "this", "->", "sender", "->", "send", "(", "$", "document", "->", "getName", "(", ")", ",", "$", "xml", ")", ";", "}" ]
Build and send document. @param DocumentInterface $document @return BaseResult
[ "Build", "and", "send", "document", "." ]
05abefedcb95cb5cf32d73a3b2995dcdd30ff668
https://github.com/giansalex/greenter/blob/05abefedcb95cb5cf32d73a3b2995dcdd30ff668/src/Greenter/Factory/FeFactory.php#L123-L128
train
giansalex/greenter
src/Greenter/See.php
See.getXmlSigned
public function getXmlSigned(DocumentInterface $document) { $classDoc = get_class($document); return $this->factory ->setBuilder($this->getBuilder($classDoc)) ->getXmlSigned($document); }
php
public function getXmlSigned(DocumentInterface $document) { $classDoc = get_class($document); return $this->factory ->setBuilder($this->getBuilder($classDoc)) ->getXmlSigned($document); }
[ "public", "function", "getXmlSigned", "(", "DocumentInterface", "$", "document", ")", "{", "$", "classDoc", "=", "get_class", "(", "$", "document", ")", ";", "return", "$", "this", "->", "factory", "->", "setBuilder", "(", "$", "this", "->", "getBuilder", "(", "$", "classDoc", ")", ")", "->", "getXmlSigned", "(", "$", "document", ")", ";", "}" ]
Get signed xml from document. @param DocumentInterface $document @return string
[ "Get", "signed", "xml", "from", "document", "." ]
05abefedcb95cb5cf32d73a3b2995dcdd30ff668
https://github.com/giansalex/greenter/blob/05abefedcb95cb5cf32d73a3b2995dcdd30ff668/src/Greenter/See.php#L151-L158
train
giansalex/greenter
src/Greenter/See.php
See.send
public function send(DocumentInterface $document) { $classDoc = get_class($document); $this->factory ->setBuilder($this->getBuilder($classDoc)) ->setSender($this->getSender($classDoc)); return $this->factory->send($document); }
php
public function send(DocumentInterface $document) { $classDoc = get_class($document); $this->factory ->setBuilder($this->getBuilder($classDoc)) ->setSender($this->getSender($classDoc)); return $this->factory->send($document); }
[ "public", "function", "send", "(", "DocumentInterface", "$", "document", ")", "{", "$", "classDoc", "=", "get_class", "(", "$", "document", ")", ";", "$", "this", "->", "factory", "->", "setBuilder", "(", "$", "this", "->", "getBuilder", "(", "$", "classDoc", ")", ")", "->", "setSender", "(", "$", "this", "->", "getSender", "(", "$", "classDoc", ")", ")", ";", "return", "$", "this", "->", "factory", "->", "send", "(", "$", "document", ")", ";", "}" ]
Envia documento. @param DocumentInterface $document @return Model\Response\BaseResult
[ "Envia", "documento", "." ]
05abefedcb95cb5cf32d73a3b2995dcdd30ff668
https://github.com/giansalex/greenter/blob/05abefedcb95cb5cf32d73a3b2995dcdd30ff668/src/Greenter/See.php#L167-L175
train
giansalex/greenter
src/Greenter/See.php
See.sendXml
public function sendXml($type, $name, $xml) { $this->factory ->setBuilder($this->getBuilder($type)) ->setSender($this->getSender($type)); return $this->factory->sendXml($name, $xml); }
php
public function sendXml($type, $name, $xml) { $this->factory ->setBuilder($this->getBuilder($type)) ->setSender($this->getSender($type)); return $this->factory->sendXml($name, $xml); }
[ "public", "function", "sendXml", "(", "$", "type", ",", "$", "name", ",", "$", "xml", ")", "{", "$", "this", "->", "factory", "->", "setBuilder", "(", "$", "this", "->", "getBuilder", "(", "$", "type", ")", ")", "->", "setSender", "(", "$", "this", "->", "getSender", "(", "$", "type", ")", ")", ";", "return", "$", "this", "->", "factory", "->", "sendXml", "(", "$", "name", ",", "$", "xml", ")", ";", "}" ]
Envia xml generado. @param string $type Document Type @param string $name Xml Name @param string $xml Xml Content @return Model\Response\BaseResult
[ "Envia", "xml", "generado", "." ]
05abefedcb95cb5cf32d73a3b2995dcdd30ff668
https://github.com/giansalex/greenter/blob/05abefedcb95cb5cf32d73a3b2995dcdd30ff668/src/Greenter/See.php#L185-L192
train
acacha/adminlte-laravel
src/stubs/LoginController.php
LoginController.attempLoginUsingUsernameAsAnEmail
protected function attempLoginUsingUsernameAsAnEmail(Request $request) { return $this->guard()->attempt( ['email' => $request->input('username'), 'password' => $request->input('password')], $request->has('remember') ); }
php
protected function attempLoginUsingUsernameAsAnEmail(Request $request) { return $this->guard()->attempt( ['email' => $request->input('username'), 'password' => $request->input('password')], $request->has('remember') ); }
[ "protected", "function", "attempLoginUsingUsernameAsAnEmail", "(", "Request", "$", "request", ")", "{", "return", "$", "this", "->", "guard", "(", ")", "->", "attempt", "(", "[", "'email'", "=>", "$", "request", "->", "input", "(", "'username'", ")", ",", "'password'", "=>", "$", "request", "->", "input", "(", "'password'", ")", "]", ",", "$", "request", "->", "has", "(", "'remember'", ")", ")", ";", "}" ]
Attempt to log the user into application using username as an email. @param \Illuminate\Http\Request $request @return bool
[ "Attempt", "to", "log", "the", "user", "into", "application", "using", "username", "as", "an", "email", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/stubs/LoginController.php#L86-L92
train
acacha/adminlte-laravel
src/Console/AdminLTEAdmin.php
AdminLTEAdmin.createAdminUser
protected function createAdminUser() { try { factory(get_class(app('App\User')))->create([ "name" => env('ADMIN_USER', $this->username()), "email" => env('ADMIN_EMAIL', $this->email()), "password" => bcrypt(env('ADMIN_PWD', '123456'))]); } catch (\Illuminate\Database\QueryException $exception) { } }
php
protected function createAdminUser() { try { factory(get_class(app('App\User')))->create([ "name" => env('ADMIN_USER', $this->username()), "email" => env('ADMIN_EMAIL', $this->email()), "password" => bcrypt(env('ADMIN_PWD', '123456'))]); } catch (\Illuminate\Database\QueryException $exception) { } }
[ "protected", "function", "createAdminUser", "(", ")", "{", "try", "{", "factory", "(", "get_class", "(", "app", "(", "'App\\User'", ")", ")", ")", "->", "create", "(", "[", "\"name\"", "=>", "env", "(", "'ADMIN_USER'", ",", "$", "this", "->", "username", "(", ")", ")", ",", "\"email\"", "=>", "env", "(", "'ADMIN_EMAIL'", ",", "$", "this", "->", "email", "(", ")", ")", ",", "\"password\"", "=>", "bcrypt", "(", "env", "(", "'ADMIN_PWD'", ",", "'123456'", ")", ")", "]", ")", ";", "}", "catch", "(", "\\", "Illuminate", "\\", "Database", "\\", "QueryException", "$", "exception", ")", "{", "}", "}" ]
Create admin user.
[ "Create", "admin", "user", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/AdminLTEAdmin.php#L41-L50
train
acacha/adminlte-laravel
src/stubs/ForgotPasswordController.php
ForgotPasswordController.sendResetLinkResponse
protected function sendResetLinkResponse(Request $request, $response) { if ($request->expectsJson()) { return response()->json([ 'status' => trans($response) ]); } return back()->with('status', trans($response)); }
php
protected function sendResetLinkResponse(Request $request, $response) { if ($request->expectsJson()) { return response()->json([ 'status' => trans($response) ]); } return back()->with('status', trans($response)); }
[ "protected", "function", "sendResetLinkResponse", "(", "Request", "$", "request", ",", "$", "response", ")", "{", "if", "(", "$", "request", "->", "expectsJson", "(", ")", ")", "{", "return", "response", "(", ")", "->", "json", "(", "[", "'status'", "=>", "trans", "(", "$", "response", ")", "]", ")", ";", "}", "return", "back", "(", ")", "->", "with", "(", "'status'", ",", "trans", "(", "$", "response", ")", ")", ";", "}" ]
Get the response for a successful password reset link. @param string $response @return mixed
[ "Get", "the", "response", "for", "a", "successful", "password", "reset", "link", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/stubs/ForgotPasswordController.php#L54-L62
train
acacha/adminlte-laravel
src/Console/Routes/ControllerRoute.php
ControllerRoute.obtainReplacements
protected function obtainReplacements() { return [ 'ROUTE_LINK' => $link = $this->getReplacements()[0], 'ROUTE_CONTROLLER' => $this->controller($this->getReplacements()[1]), 'ROUTE_METHOD' => $this->getReplacements()[2], 'ROUTE_NAME' => dot_path($link), ]; }
php
protected function obtainReplacements() { return [ 'ROUTE_LINK' => $link = $this->getReplacements()[0], 'ROUTE_CONTROLLER' => $this->controller($this->getReplacements()[1]), 'ROUTE_METHOD' => $this->getReplacements()[2], 'ROUTE_NAME' => dot_path($link), ]; }
[ "protected", "function", "obtainReplacements", "(", ")", "{", "return", "[", "'ROUTE_LINK'", "=>", "$", "link", "=", "$", "this", "->", "getReplacements", "(", ")", "[", "0", "]", ",", "'ROUTE_CONTROLLER'", "=>", "$", "this", "->", "controller", "(", "$", "this", "->", "getReplacements", "(", ")", "[", "1", "]", ")", ",", "'ROUTE_METHOD'", "=>", "$", "this", "->", "getReplacements", "(", ")", "[", "2", "]", ",", "'ROUTE_NAME'", "=>", "dot_path", "(", "$", "link", ")", ",", "]", ";", "}" ]
Obtain replacements. @return array
[ "Obtain", "replacements", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/Routes/ControllerRoute.php#L43-L51
train
acacha/adminlte-laravel
src/AdminLTE.php
AdminLTE.publicAssets
public function publicAssets() { return [ ADMINLTETEMPLATE_PATH.'/public/css' => public_path('css'), ADMINLTETEMPLATE_PATH.'/public/js' => public_path('js'), ADMINLTETEMPLATE_PATH.'/public/fonts' => public_path('fonts'), ADMINLTETEMPLATE_PATH.'/public/img' => public_path('img'), ADMINLTETEMPLATE_PATH.'/public/mix-manifest.json' => public_path('mix-manifest.json') ]; }
php
public function publicAssets() { return [ ADMINLTETEMPLATE_PATH.'/public/css' => public_path('css'), ADMINLTETEMPLATE_PATH.'/public/js' => public_path('js'), ADMINLTETEMPLATE_PATH.'/public/fonts' => public_path('fonts'), ADMINLTETEMPLATE_PATH.'/public/img' => public_path('img'), ADMINLTETEMPLATE_PATH.'/public/mix-manifest.json' => public_path('mix-manifest.json') ]; }
[ "public", "function", "publicAssets", "(", ")", "{", "return", "[", "ADMINLTETEMPLATE_PATH", ".", "'/public/css'", "=>", "public_path", "(", "'css'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/public/js'", "=>", "public_path", "(", "'js'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/public/fonts'", "=>", "public_path", "(", "'fonts'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/public/img'", "=>", "public_path", "(", "'img'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/public/mix-manifest.json'", "=>", "public_path", "(", "'mix-manifest.json'", ")", "]", ";", "}" ]
Public assets copy path. @return array
[ "Public", "assets", "copy", "path", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/AdminLTE.php#L92-L101
train
acacha/adminlte-laravel
src/AdminLTE.php
AdminLTE.views
public function views() { return [ ADMINLTETEMPLATE_PATH.'/resources/views/auth' => resource_path('views/vendor/adminlte/auth'), ADMINLTETEMPLATE_PATH.'/resources/views/errors' => resource_path('views/vendor/adminlte/errors'), ADMINLTETEMPLATE_PATH.'/resources/views/layouts' => resource_path('views/vendor/adminlte/layouts'), ADMINLTETEMPLATE_PATH.'/resources/views/home.blade.php' => resource_path('views/vendor/adminlte/home.blade.php'), ADMINLTETEMPLATE_PATH.'/resources/views/welcome.blade.php' => resource_path('views/welcome.blade.php'), ]; }
php
public function views() { return [ ADMINLTETEMPLATE_PATH.'/resources/views/auth' => resource_path('views/vendor/adminlte/auth'), ADMINLTETEMPLATE_PATH.'/resources/views/errors' => resource_path('views/vendor/adminlte/errors'), ADMINLTETEMPLATE_PATH.'/resources/views/layouts' => resource_path('views/vendor/adminlte/layouts'), ADMINLTETEMPLATE_PATH.'/resources/views/home.blade.php' => resource_path('views/vendor/adminlte/home.blade.php'), ADMINLTETEMPLATE_PATH.'/resources/views/welcome.blade.php' => resource_path('views/welcome.blade.php'), ]; }
[ "public", "function", "views", "(", ")", "{", "return", "[", "ADMINLTETEMPLATE_PATH", ".", "'/resources/views/auth'", "=>", "resource_path", "(", "'views/vendor/adminlte/auth'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/views/errors'", "=>", "resource_path", "(", "'views/vendor/adminlte/errors'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/views/layouts'", "=>", "resource_path", "(", "'views/vendor/adminlte/layouts'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/views/home.blade.php'", "=>", "resource_path", "(", "'views/vendor/adminlte/home.blade.php'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/views/welcome.blade.php'", "=>", "resource_path", "(", "'views/welcome.blade.php'", ")", ",", "]", ";", "}" ]
Views copy path. @return array
[ "Views", "copy", "path", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/AdminLTE.php#L138-L152
train
acacha/adminlte-laravel
src/AdminLTE.php
AdminLTE.resourceAssets
public function resourceAssets() { return [ ADMINLTETEMPLATE_PATH.'/resources/assets/css' => resource_path('assets/css'), ADMINLTETEMPLATE_PATH.'/resources/assets/img' => resource_path('assets/img'), ADMINLTETEMPLATE_PATH.'/resources/assets/js' => resource_path('assets/js'), ADMINLTETEMPLATE_PATH.'/webpack.mix.js' => base_path('webpack.mix.js'), ADMINLTETEMPLATE_PATH.'/package.json' => base_path('package.json'), ]; }
php
public function resourceAssets() { return [ ADMINLTETEMPLATE_PATH.'/resources/assets/css' => resource_path('assets/css'), ADMINLTETEMPLATE_PATH.'/resources/assets/img' => resource_path('assets/img'), ADMINLTETEMPLATE_PATH.'/resources/assets/js' => resource_path('assets/js'), ADMINLTETEMPLATE_PATH.'/webpack.mix.js' => base_path('webpack.mix.js'), ADMINLTETEMPLATE_PATH.'/package.json' => base_path('package.json'), ]; }
[ "public", "function", "resourceAssets", "(", ")", "{", "return", "[", "ADMINLTETEMPLATE_PATH", ".", "'/resources/assets/css'", "=>", "resource_path", "(", "'assets/css'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/assets/img'", "=>", "resource_path", "(", "'assets/img'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/resources/assets/js'", "=>", "resource_path", "(", "'assets/js'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/webpack.mix.js'", "=>", "base_path", "(", "'webpack.mix.js'", ")", ",", "ADMINLTETEMPLATE_PATH", ".", "'/package.json'", "=>", "base_path", "(", "'package.json'", ")", ",", "]", ";", "}" ]
Resource assets copy path. @return array
[ "Resource", "assets", "copy", "path", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/AdminLTE.php#L172-L181
train
acacha/adminlte-laravel
src/Console/Installable.php
Installable.install
private function install($files) { foreach ($files as $fileSrc => $fileDst) { if (file_exists($fileDst) && !$this->force && !$this->confirmOverwrite(basename($fileDst))) { return; } if ($this->files->isFile($fileSrc)) { $this->publishFile($fileSrc, $fileDst); } elseif ($this->files->isDirectory($fileSrc)) { $this->publishDirectory($fileSrc, $fileDst); } else { $this->error("Can't locate path: <{$fileSrc}>"); } } }
php
private function install($files) { foreach ($files as $fileSrc => $fileDst) { if (file_exists($fileDst) && !$this->force && !$this->confirmOverwrite(basename($fileDst))) { return; } if ($this->files->isFile($fileSrc)) { $this->publishFile($fileSrc, $fileDst); } elseif ($this->files->isDirectory($fileSrc)) { $this->publishDirectory($fileSrc, $fileDst); } else { $this->error("Can't locate path: <{$fileSrc}>"); } } }
[ "private", "function", "install", "(", "$", "files", ")", "{", "foreach", "(", "$", "files", "as", "$", "fileSrc", "=>", "$", "fileDst", ")", "{", "if", "(", "file_exists", "(", "$", "fileDst", ")", "&&", "!", "$", "this", "->", "force", "&&", "!", "$", "this", "->", "confirmOverwrite", "(", "basename", "(", "$", "fileDst", ")", ")", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "files", "->", "isFile", "(", "$", "fileSrc", ")", ")", "{", "$", "this", "->", "publishFile", "(", "$", "fileSrc", ",", "$", "fileDst", ")", ";", "}", "elseif", "(", "$", "this", "->", "files", "->", "isDirectory", "(", "$", "fileSrc", ")", ")", "{", "$", "this", "->", "publishDirectory", "(", "$", "fileSrc", ",", "$", "fileDst", ")", ";", "}", "else", "{", "$", "this", "->", "error", "(", "\"Can't locate path: <{$fileSrc}>\"", ")", ";", "}", "}", "}" ]
Install files from array. @param $files
[ "Install", "files", "from", "array", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/Installable.php#L19-L33
train
acacha/adminlte-laravel
src/Console/MakeV.php
MakeV.command
protected function command() { $api = $this->option('api') ? ' --api ' : ''; $action = $this->argument('action') ? ' ' . $this->argument('action') . ' ' : ''; return 'php artisan make:route ' . $this->argument('link') . $action . ' --type=' . $this->option('type') . ' --method=' . $this->option('method') . $api . ' -a --menu'; }
php
protected function command() { $api = $this->option('api') ? ' --api ' : ''; $action = $this->argument('action') ? ' ' . $this->argument('action') . ' ' : ''; return 'php artisan make:route ' . $this->argument('link') . $action . ' --type=' . $this->option('type') . ' --method=' . $this->option('method') . $api . ' -a --menu'; }
[ "protected", "function", "command", "(", ")", "{", "$", "api", "=", "$", "this", "->", "option", "(", "'api'", ")", "?", "' --api '", ":", "''", ";", "$", "action", "=", "$", "this", "->", "argument", "(", "'action'", ")", "?", "' '", ".", "$", "this", "->", "argument", "(", "'action'", ")", ".", "' '", ":", "''", ";", "return", "'php artisan make:route '", ".", "$", "this", "->", "argument", "(", "'link'", ")", ".", "$", "action", ".", "' --type='", ".", "$", "this", "->", "option", "(", "'type'", ")", ".", "' --method='", ".", "$", "this", "->", "option", "(", "'method'", ")", ".", "$", "api", ".", "' -a --menu'", ";", "}" ]
Obtain command. @return string
[ "Obtain", "command", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeV.php#L49-L57
train
acacha/adminlte-laravel
src/Console/Routes/Controller.php
Controller.controllerMethod
protected function controllerMethod($controllername) { if (str_contains($controller = $controllername, '@')) { return substr($controllername, strpos($controllername, '@')+1, strlen($controllername)); } return 'index'; }
php
protected function controllerMethod($controllername) { if (str_contains($controller = $controllername, '@')) { return substr($controllername, strpos($controllername, '@')+1, strlen($controllername)); } return 'index'; }
[ "protected", "function", "controllerMethod", "(", "$", "controllername", ")", "{", "if", "(", "str_contains", "(", "$", "controller", "=", "$", "controllername", ",", "'@'", ")", ")", "{", "return", "substr", "(", "$", "controllername", ",", "strpos", "(", "$", "controllername", ",", "'@'", ")", "+", "1", ",", "strlen", "(", "$", "controllername", ")", ")", ";", "}", "return", "'index'", ";", "}" ]
Get method from controller name. @param $controllername @return string
[ "Get", "method", "from", "controller", "name", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/Routes/Controller.php#L50-L56
train
acacha/adminlte-laravel
src/Console/HasEmail.php
HasEmail.email
protected function email() { if (($email = env('ADMIN_EMAIL', null)) != null) { return $email; } if (($email = git_user_email()) != null) { return $email; } return "admin@example.com"; }
php
protected function email() { if (($email = env('ADMIN_EMAIL', null)) != null) { return $email; } if (($email = git_user_email()) != null) { return $email; } return "admin@example.com"; }
[ "protected", "function", "email", "(", ")", "{", "if", "(", "(", "$", "email", "=", "env", "(", "'ADMIN_EMAIL'", ",", "null", ")", ")", "!=", "null", ")", "{", "return", "$", "email", ";", "}", "if", "(", "(", "$", "email", "=", "git_user_email", "(", ")", ")", "!=", "null", ")", "{", "return", "$", "email", ";", "}", "return", "\"admin@example.com\"", ";", "}" ]
Obtain admin email. @return bool|string
[ "Obtain", "admin", "email", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/HasEmail.php#L17-L28
train
acacha/adminlte-laravel
src/Console/HasUsername.php
HasUsername.username
public function username() { if (($username = env('ADMIN_USERNAME', null)) != null) { return $username; } if (($username = git_user_name()) != null) { return $username; } return "Admin"; }
php
public function username() { if (($username = env('ADMIN_USERNAME', null)) != null) { return $username; } if (($username = git_user_name()) != null) { return $username; } return "Admin"; }
[ "public", "function", "username", "(", ")", "{", "if", "(", "(", "$", "username", "=", "env", "(", "'ADMIN_USERNAME'", ",", "null", ")", ")", "!=", "null", ")", "{", "return", "$", "username", ";", "}", "if", "(", "(", "$", "username", "=", "git_user_name", "(", ")", ")", "!=", "null", ")", "{", "return", "$", "username", ";", "}", "return", "\"Admin\"", ";", "}" ]
Obtains username. @return mixed|null|string
[ "Obtains", "username", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/HasUsername.php#L18-L29
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.routeExists
protected function routeExists($link) { if ($this->option('api')) { return $this->apiRouteExists($link); } return $this->webRouteExists($link); }
php
protected function routeExists($link) { if ($this->option('api')) { return $this->apiRouteExists($link); } return $this->webRouteExists($link); }
[ "protected", "function", "routeExists", "(", "$", "link", ")", "{", "if", "(", "$", "this", "->", "option", "(", "'api'", ")", ")", "{", "return", "$", "this", "->", "apiRouteExists", "(", "$", "link", ")", ";", "}", "return", "$", "this", "->", "webRouteExists", "(", "$", "link", ")", ";", "}" ]
Check if route exists. @param $link @return mixed
[ "Check", "if", "route", "exists", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L153-L159
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.webRouteExists
protected function webRouteExists($link) { $link = $this->removeTrailingSlashIfExists($link); $link = $this->removeDuplicatedTrailingSlashes($link); foreach (Route::getRoutes() as $value) { if (in_array(strtoupper($this->option('method')), array_merge($value->methods(), ['ANY'])) && $value->uri() === $link) { return true; } } return false; }
php
protected function webRouteExists($link) { $link = $this->removeTrailingSlashIfExists($link); $link = $this->removeDuplicatedTrailingSlashes($link); foreach (Route::getRoutes() as $value) { if (in_array(strtoupper($this->option('method')), array_merge($value->methods(), ['ANY'])) && $value->uri() === $link) { return true; } } return false; }
[ "protected", "function", "webRouteExists", "(", "$", "link", ")", "{", "$", "link", "=", "$", "this", "->", "removeTrailingSlashIfExists", "(", "$", "link", ")", ";", "$", "link", "=", "$", "this", "->", "removeDuplicatedTrailingSlashes", "(", "$", "link", ")", ";", "foreach", "(", "Route", "::", "getRoutes", "(", ")", "as", "$", "value", ")", "{", "if", "(", "in_array", "(", "strtoupper", "(", "$", "this", "->", "option", "(", "'method'", ")", ")", ",", "array_merge", "(", "$", "value", "->", "methods", "(", ")", ",", "[", "'ANY'", "]", ")", ")", "&&", "$", "value", "->", "uri", "(", ")", "===", "$", "link", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if web route exists. @param $link @return mixed
[ "Check", "if", "web", "route", "exists", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L167-L178
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.action
protected function action() { if ($this->argument('action') != null) { return $this->argument('action'); } if (strtolower($this->option('type')) != 'regular') { return $this->argument('link') . 'Controller'; } return $this->argument('link'); }
php
protected function action() { if ($this->argument('action') != null) { return $this->argument('action'); } if (strtolower($this->option('type')) != 'regular') { return $this->argument('link') . 'Controller'; } return $this->argument('link'); }
[ "protected", "function", "action", "(", ")", "{", "if", "(", "$", "this", "->", "argument", "(", "'action'", ")", "!=", "null", ")", "{", "return", "$", "this", "->", "argument", "(", "'action'", ")", ";", "}", "if", "(", "strtolower", "(", "$", "this", "->", "option", "(", "'type'", ")", ")", "!=", "'regular'", ")", "{", "return", "$", "this", "->", "argument", "(", "'link'", ")", ".", "'Controller'", ";", "}", "return", "$", "this", "->", "argument", "(", "'link'", ")", ";", "}" ]
Get the action replacement. @return array|string
[ "Get", "the", "action", "replacement", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L278-L287
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.validateMethod
protected function validateMethod() { if (! in_array(strtoupper($this->option('method')), $methods = array_merge(Router::$verbs, ['ANY']))) { throw new MethodNotAllowedException($methods); } }
php
protected function validateMethod() { if (! in_array(strtoupper($this->option('method')), $methods = array_merge(Router::$verbs, ['ANY']))) { throw new MethodNotAllowedException($methods); } }
[ "protected", "function", "validateMethod", "(", ")", "{", "if", "(", "!", "in_array", "(", "strtoupper", "(", "$", "this", "->", "option", "(", "'method'", ")", ")", ",", "$", "methods", "=", "array_merge", "(", "Router", "::", "$", "verbs", ",", "[", "'ANY'", "]", ")", ")", ")", "{", "throw", "new", "MethodNotAllowedException", "(", "$", "methods", ")", ";", "}", "}" ]
Validate option method.
[ "Validate", "option", "method", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L301-L306
train