_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13300 | Paginator.getSummary | train | public function getSummary($separator = '-')
{
if ($this->getTotalAmount() == 0) {
return (string) 0;
} else {
return $this->getStart() . $separator . $this->getEnd();
}
} | php | {
"resource": ""
} |
q13301 | Paginator.reset | train | public function reset()
{
$this->itemsPerPage = null;
$this->currentPage = null;
$this->totalAmount = null;
$this->url = null;
return $this;
} | php | {
"resource": ""
} |
q13302 | Paginator.getPageNumbers | train | public function getPageNumbers()
{
$pages = range(1, $this->getPagesCount());
// And has an styling adapter
if ($this->getPagesCount() > 10 && $this->hasAdapter()) {
return $this->style->getPageNumbers($pages, $this->getCurrentPage());
} else {
return $pages;
}
} | php | {
"resource": ""
} |
q13303 | Paginator.setCurrentPage | train | private function setCurrentPage($currentPage, $fixRange = true)
{
if ($fixRange === true) {
if (!$this->pageInRange($currentPage)) {
$currentPage = 1;
}
}
$this->currentPage = (int) $currentPage;
return $this;
} | php | {
"resource": ""
} |
q13304 | Paginator.getPagesCount | train | private function getPagesCount()
{
if ($this->getItemsPerPage() != 0) {
return (int) abs(ceil($this->getTotalAmount() / $this->getItemsPerPage()));
} else {
return 0;
}
} | php | {
"resource": ""
} |
q13305 | Paginator.toArray | train | public function toArray()
{
return array(
'firstPage' => $this->getFirstPage(),
'lastPage' => $this->getLastPage(),
'offset' => $this->countOffset(),
'summary' => $this->getSummary(),
'hasPages' => $this->hasPages(),
'hasAdapter' => $this->hasAdapter(),
'hasNextPage' => $this->hasNextPage(),
'hasPreviousPage' => $this->hasPreviousPage(),
'nextPage' => $this->getNextPage(),
'previousPage' => $this->getPreviousPage(),
'nextPageUrl' => $this->getNextPageUrl(),
'previousPageUrl' => $this->getPreviousPageUrl(),
'currentPage' => $this->getCurrentPage(),
'perPageCount' => $this->getItemsPerPage(),
'total' => $this->getTotalAmount(),
'pageNumbers' => $this->getPageNumbers()
);
} | php | {
"resource": ""
} |
q13306 | PlatformType.getPlatformOptions | train | protected function getPlatformOptions()
{
$config = $this->getConfigs();
$options = $config->getOptions();
$platform = $config->getPlatform();
return isset($options[$platform])
? $options[$platform]
: [];
} | php | {
"resource": ""
} |
q13307 | ShoppingCartItem.getPrice | train | public function getPrice()
{
$price = $this->BasePrice;
// Check for customisations that modify price
foreach ($this->getCustomisations() as $item) {
$price += ($item->Price) ? $item->Price : 0;
}
return $price;
} | php | {
"resource": ""
} |
q13308 | ShoppingCartItem.getDiscount | train | public function getDiscount()
{
$amount = 0;
$cart = ShoppingCart::get();
$items = $cart->TotalItems;
$discount = $cart->getDiscount();
if ($this->BasePrice && $discount && $discount->Amount) {
if ($discount->Type == "Fixed") {
$amount = ($discount->Amount / $items) * $this->Quantity;
} elseif ($discount->Type == "Percentage") {
$amount = (($this->Price / 100) * $discount->Amount) * $this->Quantity;
}
}
return $amount;
} | php | {
"resource": ""
} |
q13309 | ShoppingCartItem.getTax | train | public function getTax()
{
$amount = 0;
if ($this->Price && $this->TaxRate) {
$amount = (($this->Price - $this->Discount) / 100) * $this->TaxRate;
}
return $amount;
} | php | {
"resource": ""
} |
q13310 | ShoppingCartItem.getTotalTax | train | public function getTotalTax()
{
$amount = 0;
if ($this->Price && $this->TaxRate && $this->Quantity) {
$amount = ((($this->Price * $this->Quantity) - $this->Discount) / 100) * $this->TaxRate;
}
return $amount;
} | php | {
"resource": ""
} |
q13311 | ShoppingCartItem.checkStockLevel | train | public function checkStockLevel($qty)
{
$stock_param = $this->config()->stock_param;
$item = $this->FindStockItem();
$stock = ($item->$stock_param) ? $item->$stock_param : 0;
// if not enough stock, throw an exception
if($stock < $qty) {
throw new ValidationException(_t(
"Checkout.NotEnoughStock",
"There are not enough '{title}' in stock",
"Message to show that an item hasn't got enough stock",
array('title' => $item->Title)
));
}
} | php | {
"resource": ""
} |
q13312 | FileUploader.upload | train | public function upload($destination, array $files)
{
foreach ($files as $file) {
if (!($file instanceof FileEntity)) {
// This should never occur, but it's always better not to rely on framework users
throw new LogicException(sprintf(
'Each file entity must be an instance of \Krystal\Http\FileTransfer\FileInfoInterface, but received "%s"', gettype($file)
));
}
// Gotta ensure again, UPLOAD_ERR_OK means there are no errors
if ($file->getError() == \UPLOAD_ERR_OK) {
// Start trying to move a file
if (!$this->move($destination, $file->getTmpName(), $file->getUniqueName())) {
return false;
}
} else {
// Invalid file, so that cannot be uploaded. That actually should be reported before inside validator
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q13313 | FileUploader.move | train | private function move($destination, $tmp, $filename)
{
if (!is_dir($destination)) {
// We can either create it automatically
if ($this->destinationAutoCreate === true) {
// Then make a directory (recursively if needed)
@mkdir($destination, 0777, true);
} else {
// Destination doesn't exist, and we shouldn't be creating it
throw new RuntimeException(sprintf(
'Destination folder does not exist', $destination
));
}
}
$target = sprintf('%s/%s', $destination, $filename);
// If Remote file exists and we don't want to override it, so let's stop here
if (is_file($target)) {
if (!$this->override) {
return true;
}
}
return move_uploaded_file($tmp, $target);
} | php | {
"resource": ""
} |
q13314 | Escaper.quoteIdentifier | train | public function quoteIdentifier($value)
{
if ($value instanceof Expr) {
return $value->getValue();
}
if ($value === '*') {
return $value;
}
$pieces = explode('.', $value);
foreach ($pieces as $key => $piece) {
$pieces[$key] = '`'.$piece.'`';
}
return implode('.', $pieces);
} | php | {
"resource": ""
} |
q13315 | Escaper.quote | train | public function quote($value)
{
switch (true) {
case $value === null:
return 'null';
case $value === true:
return '1';
case $value === false:
return '0';
case $value instanceof Expr:
return $value->getValue();
case is_int($value) || ctype_digit($value):
return (int) $value;
case is_float($value):
// Convert to non-locale aware float to prevent possible commas
return sprintf('%F', $value);
case is_array($value):
// Supports MVA attributes
if (!count($value)) {
return '()';
}
return '('.implode(',', $this->quoteArr($value)).')';
}
return $this->conn->quote($value);
} | php | {
"resource": ""
} |
q13316 | AbstractDigitList.setValueMap | train | protected function setValueMap(array $map)
{
$lower = array_change_key_case($map);
$this->caseSensitive = count($lower) !== count($map);
$this->valueMap = $this->caseSensitive ? $map : $lower;
} | php | {
"resource": ""
} |
q13317 | Walker.resolveReferences | train | public function resolveReferences(stdClass $schema, Uri $uri)
{
$this->resolver->initialize($schema, $uri);
return $this->doResolveReferences($schema, $uri);
} | php | {
"resource": ""
} |
q13318 | Walker.applyConstraints | train | public function applyConstraints($instance, stdClass $schema, Context $context)
{
$cacheKey = gettype($instance).spl_object_hash($schema);
$constraints = & $this->constraintsCache[$cacheKey];
if ($constraints === null) {
$version = $this->getVersion($schema);
$instanceType = Types::getPrimitiveTypeOf($instance);
$constraints = $this->registry->getConstraintsForType($version, $instanceType);
$constraints = $this->filterConstraintsForSchema($constraints, $schema);
}
foreach ($constraints as $constraint) {
$constraint->apply($instance, $schema, $context, $this);
}
} | php | {
"resource": ""
} |
q13319 | Walker.isProcessed | train | private function isProcessed(stdClass $schema, SplObjectStorage $storage)
{
if ($storage->contains($schema)) {
return true;
}
$storage->attach($schema);
return false;
} | php | {
"resource": ""
} |
q13320 | Walker.filterConstraintsForSchema | train | private function filterConstraintsForSchema(array $constraints, stdClass $schema)
{
$filtered = [];
foreach ($constraints as $constraint) {
foreach ($constraint->keywords() as $keyword) {
if (property_exists($schema, $keyword)) {
$filtered[] = $constraint;
break;
}
}
}
return $filtered;
} | php | {
"resource": ""
} |
q13321 | SlugGenerator.createUniqueNumericSlug | train | private function createUniqueNumericSlug($slug)
{
if ($this->isNumericSlug($slug)) {
// Extract last number and increment it
$number = substr($slug, -1, 1);
$number++;
// Replace with new number
$string = substr($slug, 0, strlen($slug) - 1) . $number;
return $string;
} else {
return $slug;
}
} | php | {
"resource": ""
} |
q13322 | SlugGenerator.getUniqueSlug | train | public function getUniqueSlug($callback, $slug, array $args = array())
{
if (!is_callable($callback)) {
throw new InvalidArgumentException(
sprintf('First argument must be callable, received "%s"', gettype($callback))
);
}
$count = 0;
while (true) {
$count++;
if (call_user_func_array($callback, array_merge(array($slug), $args))) {
// If dash can't be found, then add first
if (!$this->isNumericSlug($slug)) {
$slug = sprintf('%s-%s', $slug, $count);
} else {
$slug = $this->createUniqueNumericSlug($slug);
}
} else {
break;
}
}
return $slug;
} | php | {
"resource": ""
} |
q13323 | SlugGenerator.generate | train | public function generate($string)
{
if ($this->romanization === true) {
$string = $this->romanize($string);
}
$string = $this->lowercase($string);
$string = $this->removeUndesiredChars($string);
$string = $this->trim($string);
$string = $this->replaceWt($string);
$string = $this->removeExtraDashes($string);
return $string;
} | php | {
"resource": ""
} |
q13324 | Curl.init | train | public function init(array $options = array())
{
$this->ch = curl_init();
if (!empty($options)) {
$this->setOptions($options);
}
} | php | {
"resource": ""
} |
q13325 | Curl.exec | train | public function exec()
{
$result = curl_exec($this->ch);
if ($result === false) {
$this->appendError();
return false;
} else {
return $result;
}
} | php | {
"resource": ""
} |
q13326 | Curl.appendError | train | private function appendError()
{
$this->errors[(string) curl_errno($this->ch)] = curl_error($this->ch);
} | php | {
"resource": ""
} |
q13327 | TimeHelper.getMonthSequence | train | private static function getMonthSequence(array $months, $target, $withCurrent)
{
if (!in_array($target, $months)) {
throw new LogicException(
sprintf('Target month "%s" is out of range. The range must be from 01 up to 12', $target)
);
}
$collection = array();
foreach ($months as $month) {
if ($month == $target) {
if ($withCurrent === true) {
$collection[] = $month;
}
break;
} else {
$collection[] = $month;
}
}
return $collection;
} | php | {
"resource": ""
} |
q13328 | TimeHelper.getPreviousMonths | train | public static function getPreviousMonths($target, $withCurrent = true)
{
return self::getMonthSequence(array_keys(self::getMonths()), $target, $withCurrent);
} | php | {
"resource": ""
} |
q13329 | TimeHelper.getNextMonths | train | public static function getNextMonths($target, $withCurrent = true)
{
$months = array_keys(self::getMonths());
$months = array_reverse($months);
$result = self::getMonthSequence($months, $target, $withCurrent);
return array_reverse($result);
} | php | {
"resource": ""
} |
q13330 | TimeHelper.getAllMonthsByQuarter | train | public static function getAllMonthsByQuarter($quarter)
{
switch ($quarter) {
case 1:
return self::getMonthsByQuarter(1);
case 2:
return array_merge(self::getMonthsByQuarter(1), self::getMonthsByQuarter(2));
case 3:
return array_merge(self::getMonthsByQuarter(1), self::getMonthsByQuarter(2), self::getMonthsByQuarter(3));
case 4:
return array_merge(self::getMonthsByQuarter(1), self::getMonthsByQuarter(2), self::getMonthsByQuarter(3), self::getMonthsByQuarter(4));
default:
throw new LogicException(sprintf('Invalid quarter supplied - %s', $quarter));
}
} | php | {
"resource": ""
} |
q13331 | TimeHelper.getQuarter | train | public static function getQuarter($month = null)
{
if ($month === null) {
$month = date('n', abs(time()));
}
if (in_array($month, range(1, 3))) {
return 1;
}
if (in_array($month, range(4, 6))) {
return 2;
}
if (in_array($month, range(7, 9))) {
return 3;
}
if (in_array($month, range(10, 12))) {
return 4;
}
} | php | {
"resource": ""
} |
q13332 | EncoderRegistry.getEncoderForType | train | public function getEncoderForType(string $type): IEncoder
{
$normalizedType = self::normalizeType($type);
if (isset($this->encodersByType[$normalizedType])) {
return $this->encodersByType[$normalizedType];
}
if (class_exists($type)) {
if ($this->defaultObjectEncoder === null) {
throw new OutOfBoundsException('No default object encoder is registered');
}
return $this->defaultObjectEncoder;
}
if ($this->defaultScalarEncoder === null) {
throw new OutOfBoundsException('No default scalar encoder is registered');
}
return $this->defaultScalarEncoder;
} | php | {
"resource": ""
} |
q13333 | EncoderRegistry.registerEncoder | train | public function registerEncoder(string $type, IEncoder $encoder): void
{
$normalizedType = self::normalizeType($type);
$this->encodersByType[$normalizedType] = $encoder;
} | php | {
"resource": ""
} |
q13334 | Disclosure.setDisclosure | train | public function setDisclosure(string $disclosure): SecurityTxt
{
if (!$this->validDisclosure($disclosure)) {
throw new Exception('Disclosure policy must be either "full", "partial", or "none".');
}
$this->disclosure = $disclosure;
return $this;
} | php | {
"resource": ""
} |
q13335 | HostChecker.isPortOpenRepeater | train | public function isPortOpenRepeater($seconds = 15)
{
$start = time();
$instance = $this->getPingInstance();
do {
$current = time() - $start;
$latency = $instance->ping('fsockopen');
if ($latency !== false) {
return true;
}
} while ($current <= $seconds);
return false;
} | php | {
"resource": ""
} |
q13336 | HostChecker.getPingInstance | train | protected function getPingInstance()
{
if (empty($this->port)) {
throw new \InvalidArgumentException(
'Missing host port, ensure you called setPort().'
);
}
$instance = $this->createPing();
$instance
->setPort($this->port);
return $instance;
} | php | {
"resource": ""
} |
q13337 | HostChecker.createPing | train | protected function createPing()
{
if (!isset($this->host)) {
throw new \InvalidArgumentException(
'Missing hostname, unable to conduct a ping request.'
);
}
return new Ping($this->host, $this->ttl, $this->timeout);
} | php | {
"resource": ""
} |
q13338 | GitHubTaskBase.getUser | train | public function getUser()
{
$info = $this
->gitHubUserAuth()
->getStoreData();
$user = isset($info['user'])
? $info['user']
: getenv('PROJECTX_GITHUB_USER') ?: null;
if (!isset($user)) {
throw new \RuntimeException(
"GitHub authentication user is required. \r\n\n " .
'[info] Run vendor/bin/project-x github::auth to get started.'
);
}
return $user;
} | php | {
"resource": ""
} |
q13339 | GitHubTaskBase.getToken | train | public function getToken()
{
$info = $this
->gitHubUserAuth()
->getStoreData();
$token = isset($info['token'])
? $info['token']
: getenv('PROJECTX_GITHUB_TOKEN') ?: null;
if (!isset($token)) {
throw new \RuntimeException(
"GitHub user authentication token is required. \r\n\n " .
'[info] Run vendor/bin/project-x github::auth to get started.'
);
}
return $token;
} | php | {
"resource": ""
} |
q13340 | GitHubTaskBase.getGitHubUrlInfo | train | public function getGitHubUrlInfo()
{
$info = $this->getGithubInfo();
if (isset($info['url'])) {
$matches = [];
$pattern = '/(?:https?:\/\/github.com\/|git\@.+\:)([\w\/\-\_]+)/';
if (preg_match($pattern, $info['url'], $matches)) {
list($account, $repo) = explode(
DIRECTORY_SEPARATOR,
$matches[1]
);
return [
'account' => $account,
'repository' => $repo,
];
}
}
return [];
} | php | {
"resource": ""
} |
q13341 | GitHubTaskBase.hasGitFlow | train | protected function hasGitFlow()
{
$config = $this->gitConfig();
if (isset($config['gitflow prefix'])
&& !empty($config['gitflow prefix'])) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q13342 | TurtleService.reset | train | public function reset(int $scanHeight = null):JsonResponse
{
$params = [];
if (!is_null($scanHeight)) $params['scanHeight'] = $scanHeight;
return $this->rpcPost('reset', $params);
} | php | {
"resource": ""
} |
q13343 | TurtleService.createAddress | train | public function createAddress(string $secretSpendKey = null, string $publicSpendKey = null):JsonResponse
{
$params = [];
if (!is_null($secretSpendKey)) $params['secretSpendKey'] = $secretSpendKey;
if (!is_null($publicSpendKey)) $params['publicSpendKey'] = $publicSpendKey;
return $this->rpcPost('createAddress', $params);
} | php | {
"resource": ""
} |
q13344 | TurtleService.getBalance | train | public function getBalance(string $address = null):JsonResponse
{
$params = [];
if (!is_null($address)) $params['address'] = $address;
return $this->rpcPost('getBalance', $params);
} | php | {
"resource": ""
} |
q13345 | TurtleService.getBlockHashes | train | public function getBlockHashes(int $firstBlockIndex, int $blockCount):JsonResponse
{
$params = [
'firstBlockIndex' => $firstBlockIndex,
'blockCount' => $blockCount,
];
return $this->rpcPost('getBlockHashes', $params);
} | php | {
"resource": ""
} |
q13346 | TurtleService.getTransactionHashes | train | public function getTransactionHashes(
int $blockCount,
int $firstBlockIndex = null,
string $blockHash = null,
array $addresses = null,
string $paymentId = null
):JsonResponse {
$params = [
'blockCount' => $blockCount,
];
if (!is_null($firstBlockIndex)) $params['firstBlockIndex'] = $firstBlockIndex;
if (!is_null($blockHash)) $params['blockHash'] = $blockHash;
if (!is_null($addresses)) $params['addresses'] = $addresses;
if (!is_null($paymentId)) $params['paymentId'] = $paymentId;
return $this->rpcPost('getTransactionHashes', $params);
} | php | {
"resource": ""
} |
q13347 | TurtleService.getUnconfirmedTransactionHashes | train | public function getUnconfirmedTransactionHashes(array $addresses = null):JsonResponse
{
$params = [];
if (!is_null($addresses)) $params['addresses'] = $addresses;
return $this->rpcPost('getUnconfirmedTransactionHashes', $params);
} | php | {
"resource": ""
} |
q13348 | TurtleService.sendTransaction | train | public function sendTransaction(
int $anonymity,
array $transfers,
int $fee,
array $addresses = null,
int $unlockTime = null,
string $extra = null,
string $paymentId = null,
string $changeAddress = null
):JsonResponse {
$params = [
'anonymity' => $anonymity,
'transfers' => $transfers,
'fee' => $fee,
];
if (!is_null($addresses)) $params['addresses'] = $addresses;
if (!is_null($unlockTime)) $params['unlockTime'] = $unlockTime;
if (!is_null($extra)) $params['extra'] = $extra;
if (!is_null($paymentId)) $params['paymentId'] = $paymentId;
if (!is_null($changeAddress)) $params['changeAddress'] = $changeAddress;
return $this->rpcPost('sendTransaction', $params);
} | php | {
"resource": ""
} |
q13349 | TurtleService.sendFusionTransaction | train | public function sendFusionTransaction(
int $threshold,
int $anonymity,
array $addresses = null,
string $destinationAddress = null
):JsonResponse {
$params = [
'threshold' => $threshold,
'anonymity' => $anonymity,
];
if (!is_null($addresses)) $params['addresses'] = $addresses;
if (!is_null($destinationAddress)) $params['destinationAddress'] = $destinationAddress;
return $this->rpcPost('sendFusionTransaction', $params);
} | php | {
"resource": ""
} |
q13350 | TurtleService.estimateFusion | train | public function estimateFusion(int $threshold, array $addresses = null):JsonResponse
{
$params = [
'threshold' => $threshold,
];
if (!is_null($addresses)) $params['addresses'] = $addresses;
return $this->rpcPost('sendFusionTransaction', $params);
} | php | {
"resource": ""
} |
q13351 | TurtleService.createIntegratedAddress | train | public function createIntegratedAddress(string $address, string $paymentId):JsonResponse
{
$params = [
'address' => $address,
'paymentId' => $paymentId,
];
return $this->rpcPost('createIntegratedAddress', $params);
} | php | {
"resource": ""
} |
q13352 | SlideStyle.getPageNumbers | train | public function getPageNumbers(array $pages, $current)
{
$offset = $current * $this->step;
return array_slice($pages, $offset, $this->step);
} | php | {
"resource": ""
} |
q13353 | DeployBase.isVersionNumeric | train | protected function isVersionNumeric($version)
{
foreach (explode('.', $version) as $part) {
if (!is_numeric($part)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q13354 | DeployBase.incrementVersion | train | protected function incrementVersion($version, $patch_limit = 20, $minor_limit = 50)
{
if (!$this->isVersionNumeric($version)) {
throw new DeploymentRuntimeException(
'Unable to increment semantic version.'
);
}
list($major, $minor, $patch) = explode('.', $version);
if ($patch < $patch_limit) {
++$patch;
} else if ($minor < $minor_limit) {
++$minor;
$patch = 0;
} else {
++$major;
$patch = 0;
$minor = 0;
}
return "{$major}.{$minor}.{$patch}";
} | php | {
"resource": ""
} |
q13355 | ImageManager.getUploader | train | private function getUploader()
{
if (is_null($this->uploader)) {
$this->uploader = UploaderFactory::build($this->rootDir.$this->path, $this->plugins);
}
return $this->uploader;
} | php | {
"resource": ""
} |
q13356 | ImageManager.getFileHandler | train | private function getFileHandler()
{
if (is_null($this->fileHandler)) {
$path = rtrim($this->path, '/');
$this->fileHandler = new FileHandler($this->rootDir.$path);
}
return $this->fileHandler;
} | php | {
"resource": ""
} |
q13357 | ImageManager.getImageBag | train | public function getImageBag()
{
if ($this->imageBag == null) {
$this->imageBag = new ImageBag(new LocationBuilder($this->rootDir, $this->rootUrl, $this->path));
}
return $this->imageBag;
} | php | {
"resource": ""
} |
q13358 | ManyToMany.merge | train | public function merge($masterPk, $alias, array $rows, $junction, $column, $table, $pk, $columns)
{
foreach ($rows as &$row) {
$value = $row[$masterPk];
$row[$alias] = $this->getSlaveData($table, $pk, $junction, $column, $value, $columns);
}
return $rows;
} | php | {
"resource": ""
} |
q13359 | ManyToMany.getSlaveData | train | private function getSlaveData($slaveTable, $slavePk, $junction, $column, $value, $columns)
{
$ids = $this->queryJunctionTable($junction, $column, $value, '*');
if (empty($ids)) {
return array();
} else {
// Query only in case there attached IDs found
return $this->queryTable($slaveTable, $slavePk, $ids, $columns);
}
} | php | {
"resource": ""
} |
q13360 | ManyToMany.leaveOnlyCurrent | train | private function leaveOnlyCurrent(array $row, $target)
{
$result = array();
foreach ($row as $column => $value) {
if ($column != $target) {
$result[$column] = $value;
}
}
return $result;
} | php | {
"resource": ""
} |
q13361 | ManyToMany.queryJunctionTable | train | private function queryJunctionTable($table, $column, $value, $columns)
{
$rows = $this->queryTable($table, $column, array($value), $columns);
foreach ($rows as &$row) {
$row = $this->leaveOnlyCurrent($row, $column);
}
return $this->extractValues($rows);
} | php | {
"resource": ""
} |
q13362 | SqlDbConnectorFactory.createPdo | train | private function createPdo($vendor, array $options)
{
// First of all, make sure it's possible to instantiate PDO instance by vendor name
if (isset($this->map[$vendor])) {
$connector = $this->map[$vendor];
$driver = new $connector();
$builder = new InstanceBuilder();
return $builder->build('\Krystal\Db\Sql\LazyPDO', $driver->getArgs($options));
} else {
throw new RuntimeException(sprintf('Unknown database vendor name supplied "%s"', $vendor));
}
} | php | {
"resource": ""
} |
q13363 | SqlDbConnectorFactory.build | train | public function build($vendor, array $options)
{
return new Db(new QueryBuilder(), $this->createPdo($vendor, $options), $this->paginator, new QueryLogger());
} | php | {
"resource": ""
} |
q13364 | Saga.transition | train | public function transition($event): void
{
$this->apply($event, self::HANDLE_PREFIX);
$this->version++;
} | php | {
"resource": ""
} |
q13365 | FrontPageDisplays.getOption | train | protected static function getOption($optionName, $castToInt = true)
{
$optionValue = isset(self::$options[$optionName])
? self::$options[$optionName]
: get_option($optionName);
return $castToInt === true ? (int) $optionValue : $optionValue;
} | php | {
"resource": ""
} |
q13366 | GitDeploy.hasGitBranch | train | protected function hasGitBranch($branch_name)
{
$task = $this->getGitBuildStack()
->exec("rev-parse -q --verify {$branch_name}");
$result = $this->runSilentCommand($task);
return !empty($result->getMessage());
} | php | {
"resource": ""
} |
q13367 | GitDeploy.hasGitTrackedFilesChanged | train | protected function hasGitTrackedFilesChanged()
{
$task = $this->getGitBuildStack()
->exec("status --untracked-files=no --porcelain");
/** @var Result $result */
$result = $this->runSilentCommand($task);
$changes = array_filter(
explode("\n", $result->getMessage())
);
return (bool) count($changes) != 0;
} | php | {
"resource": ""
} |
q13368 | GitDeploy.askBuildVersion | train | protected function askBuildVersion()
{
$last_version = $this->gitLatestVersionTag();
$next_version = $this->incrementVersion($last_version);
$question = (new Question("Set build version [{$next_version}]: ", $next_version))
->setValidator(function ($input_version) use ($last_version) {
$input_version = trim($input_version);
if (version_compare($input_version, $last_version, '==')) {
throw new \RuntimeException(
'Build version has already been used.'
);
}
if (!$this->isVersionNumeric($input_version)) {
throw new \RuntimeException(
'Build version is not numeric.'
);
}
return $input_version;
});
return $this->doAsk($question);
} | php | {
"resource": ""
} |
q13369 | GitDeploy.runGitInitAdd | train | protected function runGitInitAdd()
{
$repo = $this->gitRepo();
$origin = $this->gitOrigin();
$branch = $this->gitBranch();
$stack = $this->getGitBuildStack();
if (!$this->buildHasGit()) {
$stack
->exec('init')
->exec("remote add {$origin} {$repo}");
if ($this->gitRemoteBranchExist()) {
$stack
->exec('fetch --all')
->exec("reset --soft {$origin}/{$branch}");
}
} else {
$stack
->checkout($branch)
->pull($origin, $branch);
}
$result = $stack
->add('.')
->run();
$this->validateTaskResult($result);
return $this;
} | php | {
"resource": ""
} |
q13370 | GitDeploy.gitRemoteBranchExist | train | protected function gitRemoteBranchExist()
{
$task = $this->getGitBuildStack()
->exec("ls-remote --exit-code --heads {$this->gitRepo()} {$this->gitBranch()}");
/** @var Result $result */
$result = $this->runSilentCommand($task);
return $result->getExitCode() === 0;
} | php | {
"resource": ""
} |
q13371 | GitDeploy.gitRepo | train | protected function gitRepo($throw_exception = true)
{
$options = $this->getOptions();
$repo = isset($options['repo_url'])
? $options['repo_url']
: null;
if (!isset($repo) && $throw_exception) {
throw new DeploymentRuntimeException(
'Missing Git repository in deploy options.'
);
}
return $repo;
} | php | {
"resource": ""
} |
q13372 | DBResourceManager.verifySelectQuery | train | protected function verifySelectQuery(SelectQuery $query) {
$this->verifyScope($query);
$this->verifyRequiredFields($query);
$this->verifyFields($query);
$this->verifyLimits($query);
} | php | {
"resource": ""
} |
q13373 | DBResourceManager.verifyRequiredFields | train | protected function verifyRequiredFields(SelectQuery $query, array $requiredFields = null) {
if ($requiredFields == null) {
$requiredFields = $this->getRequiredFields();
}
if (!empty($requiredFields)) {
foreach ($requiredFields as $requiredField) {
if (empty($query->getWhereCondition($requiredField, null, false, true))) {
throw new RuntimeException("Condition required: $requiredField");
}
}
}
} | php | {
"resource": ""
} |
q13374 | DBResourceManager.verifyFields | train | protected function verifyFields(SelectQuery $query) {
$foundField = null;
if ($this->hasOtherFields($query, null, false, $foundField)) {
throw new RuntimeException("Invalid fields on query : $foundField");
}
} | php | {
"resource": ""
} |
q13375 | DBResourceManager.verifyLimits | train | protected function verifyLimits (SelectQuery $query) {
if (empty($query->getLimit())) {
$query->limit($this->getDefaultLimit());
} else if ($query->getLimit() > $this->getMaxLimit()) {
$query->limit($this->getMaxLimit());
}
} | php | {
"resource": ""
} |
q13376 | DBResourceManager.renameSource | train | private function renameSource(Query $query, string $tableName = null):string {
if($tableName == null) {
$tableName = $this->getTableName();
}
$previusSource = $query->getTable();
if(!empty($tableName)) {
$query->table($tableName);
}
return $previusSource;
} | php | {
"resource": ""
} |
q13377 | DBResourceManager.renameConditionFields | train | private function renameConditionFields(ConditionGroup $conditionGroup, $namesMap = null, $originalSource = null, $newSource = null) {
if (!$conditionGroup->isEmpty()) {
if($namesMap == null) {
$namesMap = $this->getColumnNames();
}
$conditions = &$conditionGroup->getConditions();
foreach ($conditions as $key=>&$condition) {
switch ($condition->type) {
case ConditionType::GROUP:
$this->renameConditionFields($condition->group, $namesMap, $originalSource, $newSource);
break;
case ConditionType::BASIC:
$newName = $this->getFieldNewName($condition->field, $namesMap, $originalSource, $newSource);
if($newName != null) {
$condition->field = $newName;
}
if ($condition->operator == ConditionOperator::EQUALS_FIELD) {
$newName = $this->getFieldNewName($condition->value, $namesMap, $originalSource, $newSource);
if($newName != null) {
$condition->value = $newName;
}
}
break;
case ConditionType::RAW:
foreach ($namesMap as $fieldName => $dbName) {
$condition->sql = preg_replace('/\b' . $fieldName . '(?=$|\s)/', $dbName, $condition->sql);
$condition->sql = preg_replace('/\b' . $originalSource.$fieldName . '(?=$|\s)/', "$newSource.$dbName", $condition->sql);
}
break;
}
}
}
} | php | {
"resource": ""
} |
q13378 | DBResourceManager.renameSetFields | train | private function renameSetFields(Query $query, $columnNames, $originalSource, $newSource) {
$renamedFields = [];
foreach ($query->getFields() as $field => $value) {
$newName = $this->getFieldNewName($field, $columnNames, $originalSource, $newSource);
if($newName != null) {
$renamedFields[$newName] = $value;
}
}
$query->fields($renamedFields);
} | php | {
"resource": ""
} |
q13379 | DBResourceManager.fieldInList | train | protected function fieldInList($field, array $list) : bool {
$result = in_array($field, $list);
if (!$result && !$this->isFieldCaseSensitive()) {
$result = in_array(strtolower($field), $list);
}
return $result;
} | php | {
"resource": ""
} |
q13380 | DBResourceManager.fieldInMap | train | private function fieldInMap($field, array $map) {
$result = null;
if (array_key_exists($field, $map)) {
$result = $map[$field];
} else if (!$this->isFieldCaseSensitive()) {
$field = strtolower($field);
//$map = array_map('strtolower', $map);
if (array_key_exists($field, $map)) {
$result = $map[$field];
}
}
return $result;
} | php | {
"resource": ""
} |
q13381 | DBResourceManager.getFieldNewName | train | private function getFieldNewName($field, $namesMap = null, $originalSource = null, $newSource = null) {
$newName = null;
if ($namesMap == null) {
$namesMap = $this->getColumnNames();
}
//primero busca una entrada en el mapa para el nombre del campo indicado
$newName = $this->fieldInMap($field, $namesMap);
if (empty($newName) && $this->fieldInList($field, $namesMap)) {
$newName = $field;
}
if (empty($newName)) {
//si el field indicado comienza con nombre de tabla seguido de punto
$fieldPos = strpos($field, "$originalSource.");
if($fieldPos === 0) {
$searchField = substr($field, strlen($originalSource)+1);
$newName = $this->fieldInMap($searchField, $namesMap);
if(!empty($newName) && !empty($newSource) && strpos($newName, '.') === false) {
$newName = "$newSource.$newName";
}
}
}
if (empty($newName)) {
if (preg_match ( "/\w+\s*\(\s*(\w+)\s*\)/", $field, $matches)) {
$newName = str_replace($matches[1], $this->getFieldNewName($matches[1]), $matches[0]);
}
}
return empty($newName) ? null : $newName;
} | php | {
"resource": ""
} |
q13382 | DBResourceManager.renameSelectFields | train | private function renameSelectFields(SelectQuery $query, $namesMap = null, $originalSource = null) {
if($namesMap == null) {
$namesMap = $this->getColumnNames();
}
$selectFields = &$query->getSelectFields();
//en el caso que no se indique nada en el select, pongo los del mapa
if (empty($selectFields)) {
foreach ($namesMap as $aliasName => $columnName) {
if (is_numeric($aliasName)) {
$selectItem = $columnName;
} else if (empty($columnName) || $aliasName === $columnName) {
$selectItem = $aliasName;
} else {
$selectItem = [$columnName, $aliasName];
}
$query->select($selectItem);
}
} else {
//primer for para busqueda de * o tabla.* y agregado de campos
$newSelectFields = [];
foreach ($selectFields as $selectField) {
$aliasName = $selectField instanceof stdClass ? trim($selectField->expression) : trim($selectField);
if ($aliasName == '*') {
foreach ($namesMap as $aliasName => $columnName) {
if (is_numeric($aliasName)) {
$newSelectFields[$columnName] = $columnName;
} else {
$newSelectFields[$aliasName] = $aliasName;
}
}
continue;
} else if (!empty($originalSource) && $aliasName == "$originalSource.*") {
foreach ($namesMap as $aliasName => $columnName) {
if (is_numeric($aliasName)) {
$newSelectFields["$originalSource.$columnName"] = "$originalSource.$columnName";
} else {
$newSelectFields["$originalSource.$aliasName"] = "$originalSource.$aliasName";
}
}
continue;
} else {
$newSelectFields[$aliasName] = $selectField;
}
}
if (!empty($newSelectFields)) {
$query->selectFields(array_values($newSelectFields));
}
//segundo for para reemplazo de nombres
foreach ($selectFields as &$field) {
if ($field instanceof stdClass) {
$aliasName = $field->alias;
$columnName = $this->getFieldNewName($field->expression, $namesMap, $originalSource, $query->getTable());
} else {
$aliasName = $field;
$columnName = $this->getFieldNewName($field, $namesMap, $originalSource, $query->getTable());
}
if($columnName != null) {
if ($columnName == $aliasName) {
$field = $columnName;
} else {
$field = new stdClass();
$field->expression = $columnName;
$field->alias = $aliasName;
}
}
}
}
} | php | {
"resource": ""
} |
q13383 | DBResourceManager.renameOrderByFields | train | private function renameOrderByFields(SelectQuery $query, $namesMap = null, $originalSource = null) {
if($namesMap == null) {
$namesMap = $this->getColumnNames();
}
$orderByFields = &$query->getOrderByFields();
if (!empty($orderByFields)) {
foreach ($orderByFields as &$orderByField) {
$newName = $this->getFieldNewName($orderByField->field, $namesMap, $originalSource, $query->getTable());
if($newName != null) {
$orderByField->field = $newName;
}
}
}
} | php | {
"resource": ""
} |
q13384 | DBResourceManager.renameGroupByFields | train | private function renameGroupByFields(SelectQuery $query, $namesMap = null, $originalSource = null) {
if($namesMap == null) {
$namesMap = $this->getColumnNames();
}
$groupByFields = &$query->getGroupByFields();
if (!empty($groupByFields)) {
$source = $query->getTable();
$newGroupByFields = [];
foreach ($groupByFields as $field) {
if ($field == '*') {
foreach ($namesMap as $aliasName => $columnName) {
$newGroupByFields[$columnName] = 1;
}
continue;
} else if (!empty($originalSource) && $field == "$originalSource.*") {
foreach ($namesMap as $aliasName => $columnName) {
$newGroupByFields["$source.$columnName"] = 1;
}
continue;
} else {
$newName = $this->getFieldNewName($field, $namesMap, $originalSource, $source);
if($newName != null) {
$newGroupByFields[$newName] = 1;
}
}
}
if (!empty($newGroupByFields)) {
$query->groupByFields(array_keys($newGroupByFields));
}
}
} | php | {
"resource": ""
} |
q13385 | DBResourceManager.renameJoinFields | train | private function renameJoinFields(SelectQuery $query, $namesMap = null, $originalSource = null) {
if($namesMap == null) {
$namesMap = $this->getColumnNames();
}
$joins = &$query->getJoins();
if(!empty($joins)) {
foreach ($joins as &$join) {
$this->renameConditionFields($join, $namesMap, $originalSource, $query->getTable());
}
}
} | php | {
"resource": ""
} |
q13386 | DBResourceManager.hasOtherConditionField | train | private function hasOtherConditionField(ConditionGroup $conditionGroup, string $source, array $fieldNames, &$foundField = null) : bool {
$result = false;
$conditions = &$conditionGroup->getConditions();
foreach ($conditions as $key=>&$condition) {
if ($condition->type == ConditionType::GROUP) {
$result = $this->hasOtherConditionField($condition->group, $source, $fieldNames, $foundField);
if ($result) {
break;
}
} else if ($condition->type == ConditionType::RAW) {
$result = true;
$foundField = 'RAW';
break;
} else {
$field = $condition->field;
$tablePos = stripos($field, "$source.");
if($tablePos === 0) {
$field = substr($field, strlen($source)+1);
}
if (!$this->fieldInList($field, $fieldNames)) {
$result = true;
$foundField = $field;
break;
}
if ($condition->operator == ConditionOperator::EQUALS_FIELD) {
$field = $condition->value;
$tablePos = stripos($field, "$source.");
if($tablePos === 0) {
$field = substr($field, strlen($source)+1);
}
if (!$this->fieldInList($field, $fieldNames)) {
$result = true;
$foundField = $field;
break;
}
}
}
}
return $result;
} | php | {
"resource": ""
} |
q13387 | DefinitionParser.processData | train | private function processData($target, array $rules, $required, &$result)
{
foreach ($rules as $constraintName => $options) {
// Step first: Build constraint instance
if (isset($options['value'])) {
// When an array is provided then we should merge values and dynamically call a method
if (is_array($options['value'])) {
// Quick trick
$args = array_merge(array($constraintName), $options['value']);
$constraint = call_user_func_array(array($this->constraintFactory, 'build'), $args);
} else {
$constraint = $this->constraintFactory->build($constraintName, $options['value']);
}
} else {
$constraint = $this->constraintFactory->build($constraintName);
}
// Start tweaking the instance
if (isset($options['break'])) {
$constraint->setBreakable($options['break']);
} else {
// By default it should break the chain
$constraint->setBreakable(true);
}
// If additional message specified, then use it
// Otherwise a default constraint message is used by default
if (isset($options['message'])) {
$constraint->setMessage($options['message']);
}
$constraint->setRequired((bool) $required);
// If a $target name was not provided before
if (!isset($result[$target])) {
$result[$target] = array();
}
// Finally add prepared constraint
array_push($result[$target], $constraint);
}
} | php | {
"resource": ""
} |
q13388 | DynamicChoiceLoader.addNewValues | train | protected function addNewValues(array $selections, array $values)
{
if ($this->isAllowAdd()) {
foreach ($values as $value) {
if (!\in_array($value, $selections) && !\in_array((string) $value, $selections)) {
$selections[] = (string) $value;
}
}
}
return $selections;
} | php | {
"resource": ""
} |
q13389 | DynamicChoiceLoader.getSelectedChoices | train | protected function getSelectedChoices(array $values, $value = null)
{
$structuredValues = $this->loadChoiceList($value)->getStructuredValues();
$values = $this->forceStringValues($values);
$allChoices = [];
$choices = [];
$isGrouped = false;
foreach ($structuredValues as $group => $choice) {
// group
if (\is_array($choice)) {
$isGrouped = true;
foreach ($choice as $choiceKey => $choiceValue) {
if ($this->allChoices || \in_array($choiceValue, $values)) {
$choices[$group][$choiceKey] = $choiceValue;
$allChoices[$choiceKey] = $choiceValue;
}
}
} elseif ($this->allChoices || \in_array($choice, $values)) {
$choices[$group] = $choice;
$allChoices[$group] = $choice;
}
}
if ($this->isAllowAdd()) {
$choices = $this->addNewTagsInChoices($choices, $allChoices, $values, $isGrouped);
}
return (array) $choices;
} | php | {
"resource": ""
} |
q13390 | DynamicChoiceLoader.forceStringValues | train | protected function forceStringValues(array $values)
{
foreach ($values as $key => $value) {
$values[$key] = (string) $value;
}
return $values;
} | php | {
"resource": ""
} |
q13391 | DynamicChoiceLoader.addNewTagsInChoices | train | protected function addNewTagsInChoices(array $choices, array $allChoices, array $values, $isGrouped)
{
foreach ($values as $value) {
if (!\in_array($value, $allChoices)) {
if ($isGrouped) {
$choices['-------'][$value] = $value;
} else {
$choices[$value] = $value;
}
}
}
return $choices;
} | php | {
"resource": ""
} |
q13392 | View.render | train | public function render($data = array(), $params = array())
{
if ($this->controller->getTemplate() !== null) {
foreach ($this->controller->filters as $filter) {
$this->twig->addFilter($filter);
}
$this->twig->addGlobal('params', $params);
$key = "twig" . microtime(true);
// Debugbar::timer($key, $this->controller->getTemplate());
$template = $this->twig->load($this->controller->getTemplate());
$data = $template->render($this->getData($data));
// Debugbar::stopTimer($key);
}
return $data;
} | php | {
"resource": ""
} |
q13393 | View.mail | train | public function mail($template, $data = array(), &$css = array())
{
$this->twig->addFunction(new \Twig_SimpleFunction('css', function ($file) use (&$css) {
$css[] = $file;
}));
$template = $this->twig->loadTemplate($template);
return $template->render($data);
} | php | {
"resource": ""
} |
q13394 | ActionColumn.getCompatibilityId | train | protected function getCompatibilityId() {
$controller = $this->controller ? $this->controller : Yii::$app->controller->id;
if(strpos($controller, "/")) {
$controller = substr($controller, strpos($controller, "/") + 1);
}
return str_replace(' ', '', ucwords(str_replace('-', ' ', $controller)));
} | php | {
"resource": ""
} |
q13395 | ActionColumn.initDefaultButtons | train | protected function initDefaultButtons()
{
$controller = $this->getCompatibilityId();
if(\Yii::$app->user->checkAccess('read::' . $controller)) {
if (!isset($this->buttons['view'])) {
$this->buttons['view'] = function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [
'title' => Yii::t('yii', 'View'),
'class' => 'btn btn-xs btn-primary hidden-xs button-status-deactivate',
'data-pjax' => '0',
]);
};
}
}
if(\Yii::$app->user->checkAccess('update::' . $controller)) {
if (!isset($this->buttons['status'])) {
$this->buttons['status'] = function ($url, $model) {
if($model->status == 'active')
return Html::a('<span class="glyphicon glyphicon-remove"></span>', $url, [
'title' => Yii::t('yii', 'Deactivate'),
'onclick' => 'javascript: if(confirm("Are you sure you want to deactivate this item?")) myGrid.status($(this)); return false;',
'class' => 'btn btn-xs btn-warning hidden-xs button-status-deactivate',
'data-pjax' => '0',
]);
else
return Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => Yii::t('yii', 'Activate'),
'onclick' => 'javascript: if(confirm("Are you sure you want to activate this item?")) myGrid.status($(this)); return false;',
'class' => 'btn btn-xs btn-success hidden-xs button-status-activate',
'data-pjax' => '0',
]);
};
}
if (!isset($this->buttons['update'])) {
$this->buttons['update'] = function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => Yii::t('yii', 'Update'),
'class' => 'btn btn-xs btn-default',
'data-pjax' => '0',
]);
};
}
}
if(\Yii::$app->user->checkAccess('delete::' . $controller)) {
if (!isset($this->buttons['delete'])) {
$this->buttons['delete'] = function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => Yii::t('yii', 'Delete'),
'onclick' => 'javascript: if(confirm("Are you sure you want to delete this item?")) myGrid.status($(this)); return false;',
'class' => 'btn btn-xs btn-danger button-delete',
'data-pjax' => '0',
]);
};
}
}
} | php | {
"resource": ""
} |
q13396 | DockerService.asArray | train | public function asArray()
{
$array = [];
foreach (get_object_vars($this) as $property => $value) {
if (empty($value)) {
continue;
}
$array[$property] = $value;
}
return $array;
} | php | {
"resource": ""
} |
q13397 | Model.insert | train | public function insert($data = null)
{
$currentIndex = $this->getFieldValue($this->getIndex());
$fields = $this->getFields();
$sql1 = '';
$sql2 = '';
$args = array();
foreach ($fields as $field) {
// if($this->getFieldValue($field, $data) !== NULL)
if (in_array($field, $this->created_at_fileds)) {
$this->{$field} = now();
}
$value = $this->getFieldValue($field, $data);
$args[$field] = $value;
$sql1 .= "`$field`, ";
$sql2 .= ":$field, ";
}
if (!empty($sql1)) {
$sql1 = substr($sql1, 0, -2);
$sql2 = substr($sql2, 0, -2);
if($currentIndex) {
$this->db->removeCache($this->getCacheId($currentIndex));
}
return $this->db->insert('INSERT INTO `'.$this->table_name.'` ('.$sql1.') VALUES ('.$sql2.')', $args);
}
return false;
} | php | {
"resource": ""
} |
q13398 | Model.update | train | public function update($data = null)
{
$fields = $this->getFields();
$sql1 = '';
$args = array();
foreach ($fields as $field) {
if (in_array($field, $this->updated_at_fileds)) {
$this->{$field} = now();
}
$value = $this->getFieldValue($field, $data);
if (isset($value) && !$this->isIndex($field)) {
$args[] = $value;
$sql1 .= "`$field` = ?, ";
}
}
if (!empty($sql1)) {
$sql1 = substr($sql1, 0, -2);
$index = $this->getIndex();
$indexValue = $this->db->escape_string($this->getFieldValue($index, $data));
if (!$indexValue) {
return false;
}
$args[] = $indexValue;
return $this->db->exec("UPDATE `{$this->table_name}` SET $sql1 WHERE `$index` = ?", $args, $this->getCacheId($indexValue));
}
return false;
} | php | {
"resource": ""
} |
q13399 | Model.delete | train | public function delete($cache = null)
{
$index = $this->getIndex();
$value = $this->getFieldValue($index);
if ($value) {
if($cache) {
$this->db->removeCache($this->getCacheId($cache));
}
return $this->db->exec("DELETE FROM {$this->table_name} WHERE `$index` = ?", array($value), $this->getCacheId($value));
}
return false;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.