_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q248500
AmountCalculator.getRealGrossBase
validation
protected function getRealGrossBase(Model\SaleInterface $sale): float { // Store previous cache mode $cache = $this->cache; // Disable cache $this->cache = false; // Calculate real gross base $base = $this->calculateSaleItems($sale)->getBase(); // Restore cache mode $this->cache = $cache; return $base; }
php
{ "resource": "" }
q248501
AmountCalculator.createPercentAdjustment
validation
protected function createPercentAdjustment( Model\AdjustmentInterface $data, float $base, string $currency ): Adjustment { $this->assertAdjustmentMode($data, Model\AdjustmentModes::MODE_PERCENT); $rate = (float)$data->getAmount(); if ($data->getType() === Model\AdjustmentTypes::TYPE_TAXATION) { // Calculate taxation as ATI - NET $amount = Money::round($base * (1 + $rate / 100), $currency) - Money::round($base, $currency); } else { $amount = Money::round($base * $rate / 100, $currency); } return new Adjustment((string)$data->getDesignation(), $amount, $rate); }
php
{ "resource": "" }
q248502
AmountCalculator.assertAdjustmentType
validation
protected function assertAdjustmentType(Model\AdjustmentInterface $adjustment, string $expected): void { if ($expected !== $type = $adjustment->getType()) { throw new Exception\InvalidArgumentException("Unexpected adjustment type '$type'."); } }
php
{ "resource": "" }
q248503
AmountCalculator.assertAdjustmentMode
validation
protected function assertAdjustmentMode(Model\AdjustmentInterface $adjustment, string $expected): void { if ($expected !== $mode = $adjustment->getMode()) { throw new Exception\InvalidArgumentException("Unexpected adjustment mode '$mode'."); } }
php
{ "resource": "" }
q248504
AmountCalculator.convert
validation
protected function convert(Model\SaleInterface $sale, float $amount, string $currency, bool $round) { if ($currency === $this->converter->getDefaultCurrency()) { return $round ? Money::round($amount, $currency) : $amount; } if (null !== $rate = $sale->getExchangeRate()) { return $this ->converter ->convertWithRate($amount, $rate, $currency, $round); } $date = $this->contextProvider->getContext($sale)->getDate(); return $this ->converter ->convert($amount, $this->converter->getDefaultCurrency(), $currency, $date, $round); }
php
{ "resource": "" }
q248505
SaleItemAvailabilityValidator.validateItem
validation
private function validateItem(SaleItemInterface $item) { foreach ($item->getChildren() as $child) { $this->validateItem($child); } if ($item->isCompound()) { return; } if (null === $subject = $this->subjectHelper->resolve($item, false)) { return; } if (!$subject instanceof StockSubjectInterface) { return; } $quantity = $item->getTotalQuantity(); $availability = $this->availabilityHelper->getAvailability($subject, is_null($item->getParent())); if ($quantity < $availability->getMinimumQuantity()) { $message = $availability->getMinimumMessage(); } elseif ($quantity > $availability->getMaximumQuantity()) { $message = $availability->getMaximumMessage(); } else { return; } if (null !== $item->getParent()) { $message = $item->getDesignation() . ' : ' . $message; } throw new ValidationFailedException($message); }
php
{ "resource": "" }
q248506
Model.select
validation
public static function select($queryString = "", array $queryParams = []) { $tableName = static::tableName(); $rows = Db::query(" select $tableName.* from $tableName $queryString ", $queryParams, static::getDbName()); if ($rows === false) return false; if (empty($rows)) return new Collection([]); // Populate models $collection = []; foreach ($rows as $row) { // Populate model $model = new static; foreach ($row as $column => $val) $model->$column = $model->decodeValue($val, $column); $collection[] = $model; } return new Collection($collection); }
php
{ "resource": "" }
q248507
Model.find
validation
public static function find($id, $idColumn = null) { $tableName = static::tableName(); $idColumn = $idColumn ?: static::$idColumn; $rows = Db::query(" select * from $tableName where $idColumn = :id ", ["id" => $id], static::getDbName()); if ($rows === false) return false; if (empty($rows)) return null; // Populate model $model = new static; foreach ($rows[0] as $col => $val) $model->$col = $model->decodeValue($val, $col); return $model; }
php
{ "resource": "" }
q248508
Model.has
validation
public function has($forClass, $forColumn = null) { $refTable = static::tableName(); $forTable = $forClass::tableName(); $refColumn = static::$idColumn; $forColumn = $forColumn ?: strtolower(static::modelName())."_id"; $rows = Db::query(" select F.* from $refTable as R, $forTable as F where R.$refColumn = F.$forColumn and R.$refColumn = :id ", ["id" => $this->$refColumn], static::getDbName()); if ($rows === false) return false; if (empty($rows)) return null; // Populate model $forModel = new $forClass; foreach ($rows[0] as $col => $val) $forModel->$col = $forModel->decodeValue($val, $col); return $forModel; }
php
{ "resource": "" }
q248509
Model.hasMany
validation
public function hasMany($forClass, $forColumn = null, $condition = "", array $conditionParams = []) { $refTable = static::tableName(); $forTable = $forClass::tableName(); $refColumn = static::$idColumn; $forColumn = $forColumn ?: strtolower(static::modelName())."_id"; $rows = Db::query(" select F.* from $refTable as R, $forTable as F where R.$refColumn = F.$forColumn and R.$refColumn = :id $condition ", array_merge(["id" => $this->$refColumn], $conditionParams), static::getDbName()); if ($rows === false) return false; if (empty($rows)) return new Collection([]); // Populate models $collection = []; foreach ($rows as $row) { $forModel = new $forClass; foreach ($row as $column => $val) $forModel->$column = $forModel->decodeValue($val, $column); $collection[] = $forModel; } return new Collection($collection); }
php
{ "resource": "" }
q248510
Model.belongsTo
validation
public function belongsTo($refClass, $forColumn = null) { // Get columns $refTable = $refClass::tableName(); $forTable = static::tableName(); $refColumn = $refClass::$idColumn; $forColumn = $forColumn ?: strtolower($refClass::modelName())."_id"; $rows = Db::query(" select R.* from $refTable as R, $forTable as F where R.$refColumn = F.$forColumn and F.$forColumn = :id ", ["id" => $this->$forColumn], static::getDbName()); if ($rows === false) return false; if (empty($rows)) return null; $refModel = new $refClass; foreach ($rows[0] as $col => $val) $refModel->$col = $refModel->decodeValue($val, $col); return $refModel; }
php
{ "resource": "" }
q248511
Model.save
validation
public function save($create = false) { // Get model informations $tableName = static::tableName(); $columns = static::tableColumns(); $idColumn = static::$idColumn; $isModel = false; $into = ""; $values = ""; $updates = ""; $condition = ""; $params = []; $primaries = []; $updateCondition = ""; // Remove columns for which no value is specified foreach ($columns as $i => $column) { $name = $column["column_name"]; $key = $column["column_key"]; // Build query components if (property_exists($this, $name) && !in_array($name, static::$autos)) { $into .= "$name, "; $values .= ":$name, "; $updates .= "$name = :$name, "; $condition .= "$name = :$name and "; $params[$name] = $this->encodeValue($name); } // Primary keys used for selecting the correct row in update if (strcasecmp($key, "PRI") === 0) { $updateCondition .= "$name = :$name and "; if (property_exists($this, $name) && !in_array($name, static::$autos)) $primaries[$name] = $this->encodeValue($name); // Check if is model with id column if ($name === $idColumn) $isModel = true; } } // Remove trailing characters $into = substr($into, 0, -2); $values = substr($values, 0, -2); $updates = substr($updates, 0, -2); $condition = substr($condition, 0, -5); $updateCondition = substr($updateCondition, 0, -5); try { // Try to insert model $status = Db::query(" insert into $tableName ($into) values ($values) ", $params, static::getDbName(), false) !== false; } catch (PDOException $e) { // If force creation, then bubble up exception if ($create) throw $e; // Use exception to determine if it was a primary key conflict if ($e->getCode() === "23000" && preg_match("/.*'PRIMARY'$/", $e->getMessage())) { // Try to update model $status = Db::query(" update $tableName set $updates where $updateCondition ", $params, static::getDbName(), false) !== false; } else throw $e; } if ($status) { // Get last insert id $lastInsertId = Db::instance(static::getDbName())->lastInsertId(); if ($lastInsertId > 0) // Fetch with inserted id return static::find($lastInsertId); else // If no last inserted if try to use update condition and primary keys return static::select("where $updateCondition", $primaries, static::getDbName())->first(); } else return false; }
php
{ "resource": "" }
q248512
Model.delete
validation
public function delete() { // Table informations $tableName = static::tableName(); $columns = static::tableColumns(); $idColumn = static::$idColumn; // Use id column if possible if (isset($this->$idColumn)) { $status = Db::query(" delete from $tableName where $idColumn = :id ", ["id" => $this->$idColumn], static::getDbName(), false); } else { $condition = ""; $params = []; foreach ($columns as $column) { $name = $column["column_name"]; $key = $column["column_key"]; if (isset($this->$name)) { $condition .= "$name = :$name and "; $params[$name] = $this->encodeValue($name); } } $condition = substr($condition, 0, -5); var_dump(" delete from $tableName where $condition "); var_dump($params); $status = Db::query(" delete from $tableName where $condition ", $params, static::getDbName(), false); } return $status !== false && $status > 0; }
php
{ "resource": "" }
q248513
Model.deleteWhere
validation
public static function deleteWhere($condition = "", array $conditionParams = []) { $tableName = static::tableName(); if (empty($condition)) return Db::query("delete from $tableName", [], static::getDbName(), false); else return Db::query(" delete from $tableName where $condition ", $conditionParams, static::getDbName(), false); }
php
{ "resource": "" }
q248514
Model.tableName
validation
public static function tableName() { // Convert from camel case to underscore $cc = static::modelName(); $cc[0] = strtolower($cc[0]); return preg_replace_callback("/[A-Z]/", function($uppercase) { return "_".strtolower($uppercase[0]); }, $cc)."s"; }
php
{ "resource": "" }
q248515
Model.decodeValue
validation
protected function decodeValue($val, $column = "") { if ($column === static::$idColumn) $val = (int)$val; else if (isset(static::$casts[$column])) { switch (static::$casts[$column]) { case "object": $val = from_json($val, false); break; case "array": $val = from_json($val, true); break; default: settype($val, static::$casts[$column]); } } /// We leave it for compatibility else if (in_array($column, static::$jsons) && is_string($val)) $val = from_json($val); return $val; }
php
{ "resource": "" }
q248516
Model.encodeValue
validation
protected function encodeValue($column) { /// @todo for compatibility $val = in_array($column, static::$jsons) ? to_json($this->$column) : $this->$column; // Convert jsons into valid json strings if (isset(static::$casts[$column]) && (static::$casts[$column] === "object" || static::$casts[$column] === "array")) $val = to_json($this->$column); // Convert bools to ints if (is_bool($val)) $val = (int)$val; return $val; }
php
{ "resource": "" }
q248517
Model.tableColumns
validation
protected static function tableColumns() { // Database config global $dbConfig; $query = Db::instance(static::getDbName())->prepare(" select column_name, column_key from information_schema.columns where table_schema = :schema and table_name = :table "); $query->bindValue(":schema", $dbConfig[static::getDbName()]["schema"]); $query->bindValue(":table", static::tableName()); if ($query->execute()) return $query->fetchAll(PDO::FETCH_ASSOC); else return false; }
php
{ "resource": "" }
q248518
Request.time
validation
public function time($timestamp = false) { return $timestamp ? (new DateTime($this->time))->getTimestamp() : $this->time; }
php
{ "resource": "" }
q248519
Request.input
validation
public function input($name = null, $default = null) { return !$name ? $this->inputs : ($this->inputs[$name] ?? $default); }
php
{ "resource": "" }
q248520
Request.file
validation
public function file($name = null) { return !$name ? $this->files : ($this->files[$name] ?? null); }
php
{ "resource": "" }
q248521
Request.validateInput
validation
public function validateInput(array $rules) { foreach ($rules as $rule) if (empty($this->inputs[$rule])) return false; return true; }
php
{ "resource": "" }
q248522
Request.forward
validation
public function forward($host, array $headers = []) { // Create and run request return Curl::create($this->method, $host.$this->url, $this->inputs, array_merge($this->headers, $headers)); }
php
{ "resource": "" }
q248523
Request.current
validation
public static function current() { $url = $_SERVER["REQUEST_URI"]; $method = $_SERVER["REQUEST_METHOD"]; $time = $_SERVER["REQUEST_TIME_FLOAT"]; $headers = getallheaders() ?: []; $inputs = []; $files = []; // Populate input $raw = []; switch ($method) { case "GET": $raw = $_GET; break; case "POST": $raw = $_POST; break; default: parse_str(file_get_contents("php://input"), $raw); } foreach ($raw as $input => $val) $inputs[$input] = parse_string($val); // Populate files foreach ($_FILES as $name => $file) $files[$name] = $file; // Return request return new static( $url, $method, $time, $headers, $inputs, $files ); }
php
{ "resource": "" }
q248524
AbstractCartProvider.updateCustomerGroupAndCurrency
validation
public function updateCustomerGroupAndCurrency() { if (!$this->hasCart() || $this->cart->isLocked()) { return $this; } // Customer group if (null !== $customer = $this->cart->getCustomer()) { if ($this->cart->getCustomerGroup() !== $customer->getCustomerGroup()) { $this->cart->setCustomerGroup($customer->getCustomerGroup()); } } // Sets the default customer group if (null === $this->cart->getCustomerGroup()) { $this->cart->setCustomerGroup($this->customerProvider->getCustomerGroup()); } // Sets the currency if (null === $this->cart->getCurrency()) { $this->cart->setCurrency($this->currencyProvider->getCurrency()); } return $this; }
php
{ "resource": "" }
q248525
Response.status
validation
public function status($status = NULL) { if ($status === NULL) { return $this->status; } elseif (array_key_exists($status, Response::$messages)) { $this->status = (int)$status; $this->status_message = Response::$messages[$this->status]; return $this; } else { throw new Exception(__METHOD__ . ' unknown status value : :value', array(':value' => $status)); } }
php
{ "resource": "" }
q248526
InvoiceSubjectTrait.initializeInvoiceSubject
validation
protected function initializeInvoiceSubject() { $this->invoiceTotal = 0; $this->creditTotal = 0; $this->invoiceState = InvoiceStates::STATE_NEW; $this->invoices = new ArrayCollection(); }
php
{ "resource": "" }
q248527
InvoiceSubjectTrait.getInvoices
validation
public function getInvoices($filter = null) { if (null === $filter) { return $this->invoices; } return $this->invoices->filter(function(InvoiceInterface $invoice) use ($filter) { return $filter xor InvoiceTypes::isCredit($invoice); }); }
php
{ "resource": "" }
q248528
InvoiceSubjectTrait.getInvoicedAt
validation
public function getInvoicedAt($latest = false) { if (0 == $this->invoices->count()) { return null; } $criteria = Criteria::create(); $criteria ->andWhere(Criteria::expr()->eq('type', InvoiceTypes::TYPE_INVOICE)) ->orderBy(['createdAt' => $latest ? Criteria::DESC : Criteria::ASC]); /** @var ArrayCollection $invoices */ $invoices = $this->invoices; $invoices = $invoices->matching($criteria); /** @var InvoiceInterface $invoice */ if (false !== $invoice = $invoices->first()) { return $invoice->getCreatedAt(); } return null; }
php
{ "resource": "" }
q248529
ManyToManyRelationRecordsValueCell.setColumnForLinksLabels
validation
public function setColumnForLinksLabels($columnNameOrClosure) { if (!is_string($columnNameOrClosure) && !($columnNameOrClosure instanceof DbExpr)) { throw new \InvalidArgumentException( '$columnNameOrClosure argument must be a string or a closure' ); } $this->columnForLinksLabels = $columnNameOrClosure; return $this; }
php
{ "resource": "" }
q248530
OrderNotifyListener.watch
validation
protected function watch(OrderInterface $order) { // Abort if notify disabled or sample order if (!$order->isAutoNotify() || $order->isSample()) { return; } // Abort if sale has notification of type 'SALE_ACCEPTED' if ($order->hasNotifications(NotificationTypes::ORDER_ACCEPTED)) { return; } // Abort if state has not changed for 'ACCEPTED' if (!$this->didStateChangeTo($order, OrderStates::STATE_ACCEPTED)) { return; } $this->notify(NotificationTypes::ORDER_ACCEPTED, $order); }
php
{ "resource": "" }
q248531
AdjustmentModes.isValidMode
validation
static public function isValidMode($mode, $throw = true) { if (in_array($mode, static::getModes(), true)) { return true; } if ($throw) { throw new InvalidArgumentException('Invalid adjustment mode.'); } return false; }
php
{ "resource": "" }
q248532
AbstractPaymentRepository.getByMethodAndStatesFromDateQuery
validation
private function getByMethodAndStatesFromDateQuery() { if (null !== $this->byMethodAndStatesFromDateQuery) { return $this->byMethodAndStatesFromDateQuery; } $qb = $this->createQueryBuilder('p'); $query = $qb ->andWhere($qb->expr()->eq('p.method', ':method')) ->andWhere($qb->expr()->in('p.state', ':states')) ->andWhere($qb->expr()->gte('p.createdAt', ':date')) ->addOrderBy('p.createdAt', 'ASC') ->getQuery() ->useQueryCache(true); return $this->byMethodAndStatesFromDateQuery = $query; }
php
{ "resource": "" }
q248533
Inform_About_Content.get_users_by_meta
validation
public function get_users_by_meta( $meta_key, $meta_value = '', $meta_compare = '', $include_empty = FALSE ) { if ( $include_empty ) { #get all with the opposite value if ( in_array( $meta_compare, array( '<>', '!=' ) ) ) { $meta_compare = '='; } else { $meta_compare = '!='; } $query = new WP_User_Query( array( 'meta_key' => $meta_key, 'meta_value' => $meta_value, 'meta_compare' => $meta_compare, 'fields' => 'ID' ) ); $exclude_users = $query->get_results(); # get all users $query = new WP_User_Query( array( 'fields' => 'all_with_meta', 'exclude' => $exclude_users ) ); return $query->get_results(); } $query = new WP_User_Query( array( 'meta_key' => $meta_key, 'meta_value' => $meta_value, 'meta_compare' => $meta_compare, 'fields' => 'all_with_meta' ) ); return $query->get_results(); }
php
{ "resource": "" }
q248534
Inform_About_Content.save_transit_posts
validation
public function save_transit_posts( $new_status, $old_status, $post ) { $this->transit_posts[ $post->ID ] = array( 'old_status' => $old_status, 'new_status' => $new_status ); }
php
{ "resource": "" }
q248535
Inform_About_Content.inform_about_posts
validation
public function inform_about_posts( $post_id = FALSE ) { if ( ! $post_id ) { return $post_id; } if ( ! isset( $this->transit_posts[ $post_id ] ) ) { return $post_id; } $transit = $this->transit_posts[ $post_id ]; if ( 'publish' != $transit[ 'new_status' ] || 'publish' == $transit[ 'old_status' ] ) { return $post_id; } // get data from current post $post_data = get_post( $post_id ); // get mail from author $user = get_userdata( $post_data->post_author ); // email addresses $to = $this->get_members( $user->data->user_email, 'post' ); if ( empty( $to ) ) { return $post_id; } // email subject $subject = get_option( 'blogname' ) . ': ' . get_the_title( $post_data->ID ); // message content $message = $post_data->post_content; # create header data $headers = array(); # From: $headers[ 'From' ] = get_the_author_meta( 'display_name', $user->ID ) . ' (' . get_bloginfo( 'name' ) . ')' . ' <' . $user->data->user_email . '>'; if ( $this->options[ 'send_by_bcc' ] ) { $bcc = $to; $to = empty( $this->options[ 'bcc_to_recipient' ] ) ? get_bloginfo( 'admin_email' ) : $this->options[ 'bcc_to_recipient' ]; $headers[ 'Bcc' ] = $bcc; } $to = apply_filters( 'iac_post_to', $to, $this->options, $post_id ); $subject = apply_filters( 'iac_post_subject', $subject, $this->options, $post_id ); $message = apply_filters( 'iac_post_message', $message, $this->options, $post_id ); $headers = apply_filters( 'iac_post_headers', $headers, $this->options, $post_id ); $attachments = apply_filters( 'iac_post_attachments', array(), $this->options, $post_id ); $signature = apply_filters( 'iac_post_signature', '', $this->options, $post_id ); $this->options[ 'static_options' ][ 'object' ] = array( 'id' => $post_id, 'type' => 'post' ); $this->send_mail( $to, $subject, $this->append_signature( $message, $signature ), $headers, $attachments ); return $post_id; }
php
{ "resource": "" }
q248536
Inform_About_Content.send_mail
validation
public function send_mail( $to, $subject = '', $message = '', $headers = array(), $attachments = array() ) { if ( $this->options[ 'static_options' ][ 'mail_to_chunking' ][ 'chunking' ] === TRUE ) { // the next group of recipients $send_next_group = array(); if ( array_key_exists( 'send_next_group', $this->options[ 'static_options' ] ) ) { $object_id = $this->options[ 'static_options' ][ 'object' ][ 'id' ]; $send_next_group = $this->options[ 'static_options' ][ 'send_next_group' ][ $object_id ]; } if ( $this->options[ 'send_by_bcc' ] ) { $headers[ 'Bcc' ] = $this->get_mail_to_chunk( $headers[ 'Bcc' ], $send_next_group ); } else { $to = $this->get_mail_to_chunk( $to, $send_next_group ); } } foreach ( $headers as $k => $v ) { $headers[] = $k . ': ' . $v; unset( $headers[ $k ] ); } return wp_mail( $to, $subject, $message, $headers, $attachments ); }
php
{ "resource": "" }
q248537
Inform_About_Content.get_mail_to_chunk
validation
private function get_mail_to_chunk( $to, $send_next_group = array() ) { $object_id = $this->options[ 'static_options' ][ 'object' ][ 'id' ]; $object_type = $this->options[ 'static_options' ][ 'object' ][ 'type' ]; if ( empty( $send_next_group ) ) { // split total remaining recipient list in lists of smaller size $chunk_size = $this->options[ 'static_options' ][ 'mail_to_chunking' ][ 'chunksize' ]; $send_next_group = array_chunk( $to, $chunk_size ); } /** * Group of recipients * * @param array $send_next_group (List of next recipients to process) * @param int $object_id * @param string $object_type * * @return array */ $to = apply_filters( 'iac_email_address_chunk', array_shift( $send_next_group ), $object_id, $object_type ); $to = implode( ',', $to ); if ( ! empty( $send_next_group ) ) { wp_schedule_single_event( time() + $this->options[ 'static_options' ][ 'schedule_interval' ], 'iac_schedule_send_chunks', array( $object_id, $object_type, $send_next_group ) ); } return $to; }
php
{ "resource": "" }
q248538
Inform_About_Content.modulate_next_group
validation
private function modulate_next_group( $object_id, $object_type, $mail_to_chunks ) { if ( ! empty( $mail_to_chunks ) ) { $this->options[ 'static_options' ][ 'send_next_group' ][ $object_id ] = $mail_to_chunks; if ( $object_type == 'post' ) { // need to emulate the internal state as // it would have been triggered by a save_post() call $this->transit_posts[ $object_id ] = array( 'new_status' => 'publish', 'old_status' => 'draft' ); $this->inform_about_posts( $object_id ); } elseif ( $object_type == 'comment' ) { $this->inform_about_comment( $object_id ); } } else { //ToDo: If implemented a logger log here a error if $mail_to_chunks empty } }
php
{ "resource": "" }
q248539
Inform_About_Content.append_signature
validation
public function append_signature( $message, $signature = '' ) { if ( empty( $signature ) ) { return $message; } $separator = apply_filters( 'iac_signature_separator', str_repeat( PHP_EOL, 2 ) . '--' . PHP_EOL ); return $message . $separator . $signature; }
php
{ "resource": "" }
q248540
Inform_About_Content.sender_to_message
validation
public static function sender_to_message( $message, $options, $id ) { $author = NULL; $commenter = NULL; $parts = array(); if ( 'iac_post_message' == current_filter() ) { $post = get_post( $id ); $author = get_userdata( $post->post_author ); if ( ! is_a( $author, 'WP_User' ) ) { return $message; } $parts = array( '', # linefeed implode( ' ', array( $options[ 'static_options' ][ 'mail_string_by' ], $author->data->display_name ) ), implode( ': ', array( $options[ 'static_options' ][ 'mail_string_url' ], get_permalink( $post ) ) ) ); } elseif ( 'iac_comment_message' == current_filter() ) { $comment = get_comment( $id ); $post = get_post( $comment->comment_post_ID ); $commenter = array( 'name' => 'Annonymous' ); if ( 0 != $comment->user_id ) { $author = get_userdata( $comment->user_id ); $commenter[ 'name' ] = $author->data->display_name; } else { if ( ! empty( $comment->comment_author ) ) { $commenter[ 'name' ] = $comment->comment_author; } } $parts = array( '', #author and title implode( ' ', array( $options[ 'static_options' ][ 'mail_string_by' ], $commenter[ 'name' ], $options[ 'static_options' ][ 'mail_string_to' ], get_the_title( $post->ID ), ) ), # the posts permalink implode( ': ', array( $options[ 'static_options' ][ 'mail_string_url' ], get_permalink( $post ) ) ) ); } if ( ! empty( $parts ) ) { $message .= implode( PHP_EOL, $parts ); } return $message; }
php
{ "resource": "" }
q248541
Inform_About_Content.load_class
validation
public static function load_class( $class_name = NULL ) { // if spl_autoload_register not exist if ( NULL === $class_name ) { // load required classes foreach ( glob( dirname( __FILE__ ) . '/*.php' ) as $path ) { require_once $path; } } else { if ( 0 !== strpos( $class_name, 'Iac_' ) ) return FALSE; // if param have a class string $path = dirname( __FILE__ ) . '/class-' . $class_name . '.php'; if ( file_exists( $path ) ) { require_once $path; return TRUE; } } return FALSE; }
php
{ "resource": "" }
q248542
TransformationTargets.getTargetsForSale
validation
static public function getTargetsForSale(SaleInterface $sale) { if ($sale instanceof CartInterface) { return [static::TARGET_ORDER, static::TARGET_QUOTE]; } elseif ($sale instanceof OrderInterface) { if ($sale->getState() !== OrderStates::STATE_NEW) { return []; } return [static::TARGET_QUOTE]; } elseif ($sale instanceof QuoteInterface) { return [static::TARGET_ORDER]; } throw new InvalidArgumentException("Unexpected sale type."); }
php
{ "resource": "" }
q248543
PaymentTransitions.getAvailableTransitions
validation
static function getAvailableTransitions(PaymentInterface $payment, $admin = false) { // TODO use payum to select gateway's supported requests/actions. $transitions = []; $method = $payment->getMethod(); $state = $payment->getState(); if ($admin) { if ($method->isManual()) { switch ($state) { case PaymentStates::STATE_PENDING: $transitions[] = static::TRANSITION_CANCEL; $transitions[] = static::TRANSITION_ACCEPT; break; case PaymentStates::STATE_CAPTURED: $transitions[] = static::TRANSITION_CANCEL; $transitions[] = static::TRANSITION_HANG; $transitions[] = static::TRANSITION_REFUND; break; case PaymentStates::STATE_REFUNDED: $transitions[] = static::TRANSITION_CANCEL; $transitions[] = static::TRANSITION_HANG; $transitions[] = static::TRANSITION_ACCEPT; break; case PaymentStates::STATE_CANCELED: $transitions[] = static::TRANSITION_HANG; $transitions[] = static::TRANSITION_ACCEPT; break; } } elseif ($method->isOutstanding() || $method->isManual()) { if ($state === PaymentStates::STATE_CAPTURED) { $transitions[] = static::TRANSITION_CANCEL; } else { $transitions[] = static::TRANSITION_ACCEPT; } } else { if ($state === PaymentStates::STATE_CAPTURED) { $transitions[] = static::TRANSITION_REFUND; } if ($state === PaymentStates::STATE_PENDING) { $diff = $payment->getUpdatedAt()->diff(new \DateTime()); if (0 < $diff->days && !$diff->invert) { $transitions[] = static::TRANSITION_CANCEL; } } } } else { if ($method->isManual() && $state === PaymentStates::STATE_PENDING) { $transitions[] = static::TRANSITION_CANCEL; } } return $transitions; }
php
{ "resource": "" }
q248544
CustomerListener.onParentChange
validation
public function onParentChange(ResourceEventInterface $event) { $customer = $this->getCustomerFromEvent($event); if ($this->updateFromParent($customer)) { $this->persistenceHelper->persistAndRecompute($customer, true); } }
php
{ "resource": "" }
q248545
CustomerListener.updateFromParent
validation
protected function updateFromParent(CustomerInterface $customer) { if (!$customer->hasParent()) { // Make sure default invoice and delivery address exists. if (null === $customer->getDefaultInvoiceAddress()) { /** @var \Ekyna\Component\Commerce\Customer\Model\CustomerAddressInterface $address */ if (false !== $address = $customer->getAddresses()->first()) { $address->setInvoiceDefault(true); $this->persistenceHelper->persistAndRecompute($address, false); } } if (null === $customer->getDefaultDeliveryAddress()) { /** @var \Ekyna\Component\Commerce\Customer\Model\CustomerAddressInterface $address */ if (false !== $address = $customer->getAddresses()->first()) { $address->setDeliveryDefault(true); $this->persistenceHelper->persistAndRecompute($address, false); } } return false; } $parent = $customer->getParent(); $changed = false; // Company if (empty($customer->getCompany())) { $company = $parent->getCompany(); if ($company != $customer->getCompany()) { $customer->setCompany($company); $changed = true; } } // Customer group $group = $parent->getCustomerGroup(); if ($group !== $customer->getCustomerGroup()) { $customer->setCustomerGroup($group); $changed = true; } // Clear VAT info if (!empty($customer->getVatNumber())) { $customer->setVatNumber(null); $changed = true; } if (!empty($customer->getVatDetails())) { $customer->setVatDetails([]); $changed = true; } if ($customer->isVatValid()) { $customer->setVatValid(false); $changed = true; } // Clear payment term if (null !== $customer->getPaymentTerm()) { $customer->setPaymentTerm(null); $changed = true; } // Clear outstanding if (0 !== $customer->getOutstandingLimit()) { $customer->setOutstandingLimit(0); $changed = true; } // TODO (?) Clear balance /*if (0 !== $customer->getOutstandingBalance()) { $customer->setOutstandingBalance(0); $changed = true; }*/ return $changed; }
php
{ "resource": "" }
q248546
CustomerListener.scheduleParentChangeEvents
validation
protected function scheduleParentChangeEvents(CustomerInterface $customer) { if (!$customer->hasChildren()) { return; } foreach ($customer->getChildren() as $child) { $this->persistenceHelper->scheduleEvent(CustomerEvents::PARENT_CHANGE, $child); } }
php
{ "resource": "" }
q248547
CustomerListener.getCustomerFromEvent
validation
protected function getCustomerFromEvent(ResourceEventInterface $event) { $resource = $event->getResource(); if (!$resource instanceof CustomerInterface) { throw new InvalidArgumentException('Expected instance of ' . CustomerInterface::class); } return $resource; }
php
{ "resource": "" }
q248548
AstroDate.create
validation
public static function create( $year = null, $month = null, $day = null, $hour = null, $min = null, $sec = null, $timezone = null, $timescale = null ) { return new static($year, $month, $day, $hour, $min, $sec, $timezone, $timescale); }
php
{ "resource": "" }
q248549
AstroDate.jd
validation
public static function jd($jd, TimeScale $timescale = null) { // JD -> Y-M-D H:M:S.m $t = []; IAU::D2dtf($timescale, 14, $jd, 0, $y, $m, $d, $t); // Create new instance from date/time components return new static($y, $m, $d, $t[0], $t[1], $t[2], null, $timescale); }
php
{ "resource": "" }
q248550
AstroDate.now
validation
public static function now($timezone = null) { // Get current time as micro unix timestamp $now = explode(' ', microtime()); $unix = $now[1]; $micro = Time::sec($now[0]); // Compoute JD from unix timestamp $jd = ($unix / 86400.0) + static::UJD; // Add timezone if none present if ($timezone == null) { $timezone = TimeZone::UTC(); } if (is_string($timezone)) { $timezone = TimeZone::parse($timezone); } // Return the new date adding the micro portion and provided timezone return static::jd($jd)->add($micro)->setTimezone($timezone); }
php
{ "resource": "" }
q248551
AstroDate.solsticeSummer
validation
public static function solsticeSummer($year) { $jd = static::solsticeJune((int)$year, false); return AstroDate::jd($jd, TimeScale::TT()); }
php
{ "resource": "" }
q248552
AstroDate.solsticeWinter
validation
public static function solsticeWinter($year) { $jd = static::solsticeDecember((int)$year, false); return AstroDate::jd($jd, TimeScale::TT()); }
php
{ "resource": "" }
q248553
AstroDate.equinoxAutumn
validation
public static function equinoxAutumn($year) { $jd = static::equinoxSeptember((int)$year, false); return AstroDate::jd($jd, TimeScale::TT()); }
php
{ "resource": "" }
q248554
AstroDate.setDate
validation
public function setDate($year, $month, $day) { $status = IAU::Cal2jd((int)$year, (int)$month, (int)$day, $djm0, $djm); $this->checkDate($status); // Check date is valid $this->jd = $djm0 + $djm; // Only set JD, keep day frac to save time return $this; }
php
{ "resource": "" }
q248555
AstroDate.setTime
validation
public function setTime($hour, $min, $sec) { $status = IAU::Tf2d('+', (int)$hour, (int)$min, (float)$sec, $days); $this->checkTime($status); // Check time is valid $this->dayFrac = $days; // Only set the day fraction return $this; }
php
{ "resource": "" }
q248556
AstroDate.setDateTime
validation
public function setDateTime($year, $month, $day, $hour, $min, $sec) { return $this->setDate($year, $month, $day)->setTime($hour, $min, $sec); }
php
{ "resource": "" }
q248557
AstroDate.setTimezone
validation
public function setTimezone($timezone) { // Check type, and parse string if present if (is_string($timezone)) { $timezone = TimeZone::parse($timezone); } else { if ($timezone instanceof TimeZone == false) { throw new \InvalidArgumentException(); } } // Convert back to UTC //$this->toUTC(); // Compute new UTC offset $jd = $this->toJD(); $tzOffset = $timezone->offset($jd) - $this->timezone->offset($jd); $this->add(Time::hours($tzOffset)); // Set the timezone $this->timezone = $timezone; $this->timezone0 = $timezone; return $this; }
php
{ "resource": "" }
q248558
AstroDate.toJD
validation
public function toJD($scale = null) { if ($scale) { return bcadd((string)$this->jd, (string)$this->dayFrac, $scale); } else { return $this->jd + $this->dayFrac; } }
php
{ "resource": "" }
q248559
AstroDate.toMJD
validation
public function toMJD($scale = null) { $mjd = static::MJD; if ($scale) { return bcsub(bcadd($this->jd, $this->dayFrac, $scale), $mjd, $scale); } else { return $this->jd + $this->dayFrac - $mjd; } }
php
{ "resource": "" }
q248560
AstroDate.add
validation
public function add(Time $t) { // Interval to add as days $td = $t->days; // Days (jda) and day fraction (dfa) to add $jda = intval($td); $dfa = $this->dayFrac + $td - $jda; // Handle the event that the day fraction becomes negative if ($dfa < 0) { $dfa += 1; $jda -= 1; } // Additional day to add from above day frac in excess of 1 day $jda1 = intval($dfa); // Since additional day has been added, modulate day frac to range 0-1 $dfa = fmod($dfa, 1); // Add the intervals $this->jd = $this->jd + $jda + $jda1; $this->dayFrac = $dfa; return $this; }
php
{ "resource": "" }
q248561
AstroDate.diff
validation
public function diff(AstroDate $b) { $prec = 12; $jd1 = $this->toJD($prec); $jd2 = $b->toJD($prec); $days = bcsub($jd1, $jd2, $prec); return Time::days(-1 * $days); }
php
{ "resource": "" }
q248562
AstroDate.dayOfYear
validation
public function dayOfYear() { $k = $this->isLeapYear() ? 1 : 2; $n = intval(275 * (int)$this->month / 9) - $k * intval(((int)$this->month + 9) / 12) + (int)$this->day - 30; return (int)$n; }
php
{ "resource": "" }
q248563
AstroDate.sidereal
validation
public function sidereal($mode = 'a', Angle $lon = null) { // Get UT1 time $ut = $this->copy()->toUT1(); $uta = $ut->jd; $utb = $ut->dayFrac; $ut = null; // Get TT time $tt = $this->copy()->toTT(); $tta = $tt->jd; $ttb = $tt->dayFrac; $tt = null; // Compute either GMST or GAST $st; if ($mode == 'a') { $strad = IAU::Gst06a($uta, $utb, $tta, $ttb); } else { $strad = IAU::Gmst06($uta, $utb, $tta, $ttb); } // Add longitude if relevant if ($lon) { $st = Angle::rad($strad)->add($lon)->norm()->toTime(); } else { $st = Angle::rad($strad)->toTime(); } // Return as hours return $st; }
php
{ "resource": "" }
q248564
AstroDate.checkDate
validation
protected function checkDate($status) { switch ($status) { case 3: // Ignore dubious year //throw new Exception('time is after end of day and dubious year'); case 2: throw new Exception('time is after end of day'); //case 1: // Ignore dubious year //throw new Exception('dubious year'); case -1: throw new Exception('bad year'); case -2: throw new Exception('bad month'); case -3: throw new Exception('bad day'); case -4: throw new Exception('bad hour'); case -5: throw new Exception('bad minute'); case -6: throw new Exception('bad second'); default: return; } }
php
{ "resource": "" }
q248565
AstroDate.getComponent
validation
protected function getComponent($e) { // JD -> Date $ihmsf = []; IAU::D2dtf($this->timescale, $this->prec - 2, $this->jd, $this->dayFrac, $iy, $im, $id, $ihmsf); switch ($e) { case 'year': return $iy; case 'month': return $im; case 'day': return $id; case 'hour': return $ihmsf[0]; case 'min': return $ihmsf[1]; case 'sec': return $ihmsf[2]; case 'micro': return $ihmsf[3]; } }
php
{ "resource": "" }
q248566
TaggedCacheForDbSelects.cachingIsPossible
validation
protected function cachingIsPossible() { if (static::$_cachingIsPossible === null) { /** @var \AlternativeLaravelCache\Core\AlternativeCacheStore $cache */ $storeClass = '\AlternativeLaravelCache\Core\AlternativeCacheStore'; $poolInterface = '\Cache\Taggable\TaggablePoolInterface'; $cache = app('cache.store')->getStore(); static::$_cachingIsPossible = ( $cache instanceof $storeClass && $cache->getWrappedConnection() instanceof $poolInterface ); } return static::$_cachingIsPossible; }
php
{ "resource": "" }
q248567
LoadMetadataListener.configureTaxableMapping
validation
private function configureTaxableMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, Pricing\Model\TaxableInterface::class)) { return; } // Don't add twice if (in_array($class, $this->taxableClassCache)) { return; } if (!$metadata->hasAssociation('taxGroup')) { $metadata->mapManyToOne([ 'fieldName' => 'taxGroup', 'targetEntity' => Pricing\Entity\TaxGroup::class, 'joinColumns' => [ [ 'name' => 'tax_group_id', 'referencedColumnName' => 'id', 'onDelete' => 'RESTRICT', 'nullable' => true, ], ], ]); } // Cache class $this->taxableClassCache[] = $class; }
php
{ "resource": "" }
q248568
LoadMetadataListener.configureIdentityMapping
validation
private function configureIdentityMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, IdentityInterface::class)) { return; } // Don't add twice if (in_array($class, $this->identityClassCache)) { return; } // Add mappings $this->addMappings($metadata, $this->getIdentityMappings()); // Cache class $this->identityClassCache[] = $class; }
php
{ "resource": "" }
q248569
LoadMetadataListener.configureVatNumberSubjectMapping
validation
private function configureVatNumberSubjectMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, Pricing\Model\VatNumberSubjectInterface::class)) { return; } // Don't add twice if (in_array($class, $this->vatNumberSubjectClassCache)) { return; } // Add mappings $this->addMappings($metadata, $this->getVatNumberSubjectMappings()); // Cache class $this->vatNumberSubjectClassCache[] = $class; }
php
{ "resource": "" }
q248570
LoadMetadataListener.configurePaymentTermSubjectMapping
validation
private function configurePaymentTermSubjectMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, Payment\PaymentTermSubjectInterface::class)) { return; } // Don't add twice if (in_array($class, $this->paymentTermSubjectClassCache)) { return; } if (!$metadata->hasAssociation('paymentTerm')) { $metadata->mapManyToOne([ 'fieldName' => 'paymentTerm', 'targetEntity' => Payment\PaymentTermInterface::class, 'joinColumns' => [ [ 'name' => 'payment_term_id', 'referencedColumnName' => 'id', 'onDelete' => 'RESTRICT', 'nullable' => true, ], ], ]); } // Cache class $this->paymentTermSubjectClassCache[] = $class; }
php
{ "resource": "" }
q248571
LoadMetadataListener.configureSubjectRelativeMapping
validation
private function configureSubjectRelativeMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, SubjectRelativeInterface::class)) { return; } // Don't add twice if (in_array($class, $this->relativeClassCache)) { return; } // Map embedded $this ->getSubjectIdentityMapper($eventArgs->getEntityManager()) ->processClassMetadata($metadata, 'subjectIdentity', 'subject_'); // Cache class $this->relativeClassCache[] = $class; }
php
{ "resource": "" }
q248572
LoadMetadataListener.configureStockSubjectMapping
validation
private function configureStockSubjectMapping(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); $class = $metadata->getName(); // Check class if (!is_subclass_of($class, Stock\StockSubjectInterface::class)) { return; } // Don't add twice if (in_array($class, $this->stockClassCache)) { return; } // Add mappings $this->addMappings($metadata, $this->getStockSubjectMappings()); // Cache class $this->stockClassCache[] = $class; }
php
{ "resource": "" }
q248573
LoadMetadataListener.configureStockUnitDiscriminatorMap
validation
private function configureStockUnitDiscriminatorMap(LoadClassMetadataEventArgs $eventArgs) { /** @var ClassMetadata $metadata */ $metadata = $eventArgs->getClassMetadata(); if (!is_subclass_of($metadata->name, Stock\StockUnitInterface::class)) { return; } $this ->getStockUnitMapper($eventArgs->getEntityManager()) ->processClassMetadata($metadata); }
php
{ "resource": "" }
q248574
LoadMetadataListener.getStockUnitMapper
validation
private function getStockUnitMapper(EntityManagerInterface $em) { if (null === $this->stockUnitMapper) { $this->stockUnitMapper = new DiscriminatorMapper($em, AbstractStockUnit::class); } return $this->stockUnitMapper; }
php
{ "resource": "" }
q248575
LoadMetadataListener.getSubjectIdentityMapper
validation
private function getSubjectIdentityMapper(EntityManagerInterface $em) { if (null === $this->subjectIdentityMapper) { $this->subjectIdentityMapper = new EmbeddableMapper($em, SubjectIdentity::class); } return $this->subjectIdentityMapper; }
php
{ "resource": "" }
q248576
LoadMetadataListener.addMappings
validation
private function addMappings(ClassMetadata $metadata, array $mappings) { foreach ($mappings as $mapping) { if (!$metadata->hasField($mapping['fieldName'])) { $metadata->mapField($mapping); } } }
php
{ "resource": "" }
q248577
LoadMetadataListener.getStockSubjectMappings
validation
private function getStockSubjectMappings() { return [ [ 'fieldName' => 'stockMode', 'columnName' => 'stock_mode', 'type' => 'string', 'length' => 16, 'nullable' => false, 'default' => Stock\StockSubjectModes::MODE_AUTO, ], [ 'fieldName' => 'stockState', 'columnName' => 'stock_state', 'type' => 'string', 'length' => 16, 'nullable' => false, 'default' => Stock\StockSubjectStates::STATE_OUT_OF_STOCK, ], [ 'fieldName' => 'stockFloor', 'columnName' => 'stock_floor', 'type' => 'decimal', 'precision' => 10, 'scale' => 3, 'nullable' => true, 'default' => 0, ], [ 'fieldName' => 'inStock', 'columnName' => 'in_stock', 'type' => 'decimal', 'precision' => 10, 'scale' => 3, 'nullable' => false, 'default' => 0, ], [ 'fieldName' => 'availableStock', 'columnName' => 'available_stock', 'type' => 'decimal', 'precision' => 10, 'scale' => 3, 'nullable' => false, 'default' => 0, ], [ 'fieldName' => 'virtualStock', 'columnName' => 'virtual_stock', 'type' => 'decimal', 'precision' => 10, 'scale' => 3, 'nullable' => false, 'default' => 0, ], [ 'fieldName' => 'replenishmentTime', 'columnName' => 'replenishment_time', 'type' => 'smallint', 'nullable' => false, 'default' => 7, ], [ 'fieldName' => 'estimatedDateOfArrival', 'columnName' => 'estimated_date_of_arrival', 'type' => 'datetime', 'nullable' => true, ], [ 'fieldName' => 'geocode', 'columnName' => 'geocode', 'type' => 'string', 'length' => 16, 'nullable' => true, ], [ 'fieldName' => 'minimumOrderQuantity', 'columnName' => 'minimum_order_quantity', 'type' => 'decimal', 'precision' => 10, 'scale' => 3, 'nullable' => false, 'default' => 1, ], [ 'fieldName' => 'quoteOnly', 'columnName' => 'quote_only', 'type' => 'boolean', 'nullable' => false, 'default' => false, ], [ 'fieldName' => 'endOfLife', 'columnName' => 'end_of_life', 'type' => 'boolean', 'nullable' => false, 'default' => false, ], ]; }
php
{ "resource": "" }
q248578
TelegramDriver.createClient
validation
public function createClient(): TgLog { $this->loop = Factory::create(); $handler = new HttpClientRequestHandler($this->loop); return new TgLog($this->token, $handler); }
php
{ "resource": "" }
q248579
TelegramDriver.createEvent
validation
public function createEvent(Request $request): Event { if (empty($request->input())) { return new Unknown(); } $update = new Update($request->input()); $this->update = $update; if ($message = $update->message) { $chat = new Chat((string) $message->chat->id, $message->chat->title, $message->chat->type); $from = new User((string) $message->from->id, $message->from->first_name, $message->from->username); return new MessageReceived( $chat, $from, $message->text, $message->location, null, optional($update->callback_query)->data, $update ); } if ($callbackQuery = $update->callback_query) { $message = $callbackQuery->message; $chat = new Chat((string) $message->chat->id, $message->chat->title, $message->chat->type); $from = new User((string) $message->chat->id, $message->from->first_name, $message->from->username); return new MessageReceived( $chat, $from, $message->text, $message->location, null, $callbackQuery->data, $update ); } return new Unknown(); }
php
{ "resource": "" }
q248580
TelegramDriver.sendMessage
validation
public function sendMessage(Chat $chat, User $recipient, string $text, Template $template = null): void { $sendMessage = new SendMessage(); if ($template !== null) { $sendMessage->reply_markup = $this->templateCompiler->compile($template); } $sendMessage->chat_id = $chat->getId(); $sendMessage->text = $text; $this->client->performApiRequest($sendMessage); $this->loop->run(); }
php
{ "resource": "" }
q248581
TelegramDriver.sendAttachment
validation
public function sendAttachment(Chat $chat, User $recipient, Attachment $attachment): void { $type = $attachment->getType(); $request = null; switch ($type) { case Attachment::TYPE_FILE: $request = new SendDocument(); $request->document = new InputFile($attachment->getPath()); $request->caption = $attachment->getParameters()->get('caption'); break; case Attachment::TYPE_IMAGE: $request = new SendPhoto(); $request->caption = $attachment->getParameters()->get('caption'); break; case Attachment::TYPE_AUDIO: $request = new SendAudio(); $request->chat_id = $chat->getId(); $request->caption = $attachment->getParameters()->get('caption'); $request->duration = $attachment->getParameters()->get('duration'); $request->performer = $attachment->getParameters()->get('performer'); $request->title = $attachment->getParameters()->get('title'); break; case Attachment::TYPE_VIDEO: $request = new SendVideo(); $request->duration = $attachment->getParameters()->get('duration'); $request->width = $attachment->getParameters()->get('width'); $request->height = $attachment->getParameters()->get('height'); $request->caption = $attachment->getParameters()->get('caption'); break; } if ($request) { $request->chat_id = $chat->getId(); $request->disable_notification = $attachment->getParameters()->get('disable_notification'); $request->reply_to_message_id = $attachment->getParameters()->get('reply_to_message_id'); $request->reply_markup = $attachment->getParameters()->get('reply_markup'); $this->client->performApiRequest($request); $this->loop->run(); } }
php
{ "resource": "" }
q248582
AbstractListener.assertDeletable
validation
protected function assertDeletable(ResourceInterface $resource) { if ($resource instanceof Model\SupplierOrderItemInterface) { if (null === $stockUnit = $resource->getStockUnit()) { return; } if (0 < $stockUnit->getShippedQuantity()) { throw new Exception\IllegalOperationException( "Supplier delivery can't be removed as at least one ". "of its items is linked to a shipped stock unit." ); // TODO message as translation id } } elseif ($resource instanceof Model\SupplierOrderInterface) { foreach ($resource->getItems() as $item) { $this->assertDeletable($item); } } elseif ($resource instanceof Model\SupplierDeliveryItemInterface) { $this->assertDeletable($resource->getOrderItem()); } elseif ($resource instanceof Model\SupplierDeliveryInterface) { foreach ($resource->getItems() as $item) { $this->assertDeletable($item); } } else { throw new Exception\InvalidArgumentException("Unexpected resource."); // TODO message as translation id } }
php
{ "resource": "" }
q248583
AbstractListener.scheduleSupplierOrderContentChangeEvent
validation
protected function scheduleSupplierOrderContentChangeEvent(Model\SupplierOrderInterface $order) { $this->persistenceHelper->scheduleEvent(SupplierOrderEvents::CONTENT_CHANGE, $order); }
php
{ "resource": "" }
q248584
StockSubjectTrait.initializeStock
validation
protected function initializeStock() { $this->stockMode = StockSubjectModes::MODE_AUTO; $this->stockState = StockSubjectStates::STATE_OUT_OF_STOCK; $this->stockFloor = 0; $this->inStock = 0; $this->availableStock = 0; $this->virtualStock = 0; $this->replenishmentTime = 2; $this->minimumOrderQuantity = 1; $this->quoteOnly = false; $this->endOfLife = false; }
php
{ "resource": "" }
q248585
AbstractShipmentListener.preventForbiddenChange
validation
protected function preventForbiddenChange(ShipmentInterface $shipment) { if ($this->persistenceHelper->isChanged($shipment, 'return')) { list($old, $new) = $this->persistenceHelper->getChangeSet($shipment, 'return'); if ($old != $new) { throw new RuntimeException("Changing the shipment type is not yet supported."); } } }
php
{ "resource": "" }
q248586
FormInput.modifySubmitedValueBeforeValidation
validation
public function modifySubmitedValueBeforeValidation($value, array $data) { if ($this->hasSubmittedValueModifier()) { return call_user_func($this->getSubmittedValueModifier(), $value, $data); } else { return $value; } }
php
{ "resource": "" }
q248587
SupplierUtil.calculateReceivedQuantity
validation
static public function calculateReceivedQuantity(SupplierOrderItemInterface $item) { $quantity = 0; foreach ($item->getOrder()->getDeliveries() as $delivery) { foreach ($delivery->getItems() as $deliveryItem) { if ($item === $deliveryItem->getOrderItem()) { $quantity += $deliveryItem->getQuantity(); continue 2; } } } return $quantity; }
php
{ "resource": "" }
q248588
SupplierUtil.calculateDeliveryRemainingQuantity
validation
static public function calculateDeliveryRemainingQuantity($item) { if ($item instanceof SupplierOrderItemInterface) { return $item->getQuantity() - static::calculateReceivedQuantity($item); } if (!$item instanceof SupplierDeliveryItemInterface) { throw new InvalidArgumentException( "Expected instance of " . SupplierOrderItemInterface::class . " or " . SupplierDeliveryItemInterface::class ); } $orderItem = $item->getOrderItem(); $result = $orderItem->getQuantity() - static::calculateReceivedQuantity($orderItem); if (0 < $item->getQuantity()) { $result += $item->getQuantity(); } return $result; }
php
{ "resource": "" }
q248589
ShipmentNotifyListener.watch
validation
protected function watch(OrderShipmentInterface $shipment) { $order = $shipment->getOrder(); // Abort if notify disabled if (!$order->isAutoNotify()) { return; } if ($shipment->isReturn()) { // If state is 'PENDING' if ($shipment->getState() === ShipmentStates::STATE_PENDING) { // Abort if shipment state has not changed for 'PENDING' if (!$this->didStateChangeTo($shipment, ShipmentStates::STATE_PENDING)) { return; } // Abort if sale has notification of type 'RETURN_PENDING' with same shipment number if ($this->hasNotification($order, NotificationTypes::RETURN_PENDING, $shipment->getNumber())) { return; } $this->notify(NotificationTypes::RETURN_PENDING, $shipment); return; } // Else if state has changed for 'RETURNED' if ($shipment->getState() === ShipmentStates::STATE_RETURNED) { // Abort if shipment state has not changed for 'RETURNED' if (!$this->didStateChangeTo($shipment, ShipmentStates::STATE_RETURNED)) { return; } // Abort if sale has notification of type 'RETURN_RECEIVED' with same shipment number if ($this->hasNotification($order, NotificationTypes::RETURN_RECEIVED, $shipment->getNumber())) { return; } $this->notify(NotificationTypes::RETURN_RECEIVED, $shipment); } return; } // Abort if shipment state has not changed for 'SHIPPED' if (!$this->didStateChangeTo($shipment, ShipmentStates::STATE_SHIPPED)) { return; } // Abort if sale has notification of type 'SHIPMENT_SHIPPED' with same shipment number if ($this->hasNotification($order, NotificationTypes::SHIPMENT_SHIPPED, $shipment->getNumber())) { return; } // Abort if sale has notification of type 'SHIPMENT_PARTIAL' with same shipment number if ($this->hasNotification($order, NotificationTypes::SHIPMENT_SHIPPED, $shipment->getNumber())) { return; } $type = NotificationTypes::SHIPMENT_SHIPPED; if ($order->getShipmentState() !== ShipmentStates::STATE_COMPLETED) { $type = NotificationTypes::SHIPMENT_PARTIAL; } $this->notify($type, $shipment); }
php
{ "resource": "" }
q248590
ShipmentNotifyListener.hasNotification
validation
protected function hasNotification(SaleInterface $sale, $type, $number) { foreach ($sale->getNotifications() as $n) { if ($n->getType() !== $type) { continue; } if ($n->hasData('shipment') && $n->getData('shipment') === $number) { return true; } } return false; }
php
{ "resource": "" }
q248591
PaymentSubjectTrait.initializePaymentSubject
validation
protected function initializePaymentSubject() { $this->depositTotal = 0; $this->grandTotal = 0; $this->paidTotal = 0; $this->pendingTotal = 0; $this->outstandingAccepted = 0; $this->outstandingExpired = 0; $this->outstandingLimit = 0; $this->paymentState = PaymentStates::STATE_NEW; $this->payments = new ArrayCollection(); }
php
{ "resource": "" }
q248592
PaymentSubjectTrait.isPaid
validation
public function isPaid() { // TRUE If paid total is greater than or equals grand total return 0 <= Money::compare($this->paidTotal, $this->grandTotal, $this->getCurrency()->getCode()); }
php
{ "resource": "" }
q248593
PaymentSubjectTrait.getRemainingAmount
validation
public function getRemainingAmount() { $amount = 0; $currency = $this->getCurrency()->getCode(); $hasDeposit = 1 === Money::compare($this->depositTotal, 0, $currency); // If deposit total is greater than zero and paid total is lower than deposit total if ($hasDeposit && (-1 === Money::compare($this->paidTotal, $this->depositTotal, $currency))) { // Pay deposit $total = $this->depositTotal; } else { // Pay grand total $total = $this->grandTotal; } $c = Money::compare($total, $this->paidTotal + $this->outstandingAccepted + $this->pendingTotal, $currency); // If (paid total + accepted outstanding + pending total) is lower limit if (1 === $c) { // Pay difference $amount = $total - $this->paidTotal - $this->outstandingAccepted - $this->pendingTotal; } else if (0 === $c && 0 < $this->outstandingAccepted) { // Pay outstanding $amount = $this->outstandingAccepted; } if (0 < $amount) { return $amount; } return 0; }
php
{ "resource": "" }
q248594
SubjectHelper.getProvider
validation
protected function getProvider($nameOrRelativeOrSubject) { if (null === $provider = $this->registry->getProvider($nameOrRelativeOrSubject)) { throw new SubjectException('Failed to get provider.'); } return $provider; }
php
{ "resource": "" }
q248595
SubjectHelper.getUrl
validation
protected function getUrl($name, $subject, $path) { if ($subject instanceof SubjectRelativeInterface) { if (null === $subject = $this->resolve($subject, false)) { return null; } } if (!$subject instanceof SubjectInterface) { throw new InvalidArgumentException("Expected instance of " . SubjectInterface::class); } // TODO Cache $event = new SubjectUrlEvent($subject, $path); $this->eventDispatcher->dispatch($name, $event); return $event->getUrl(); }
php
{ "resource": "" }
q248596
Label.isValidSize
validation
public static function isValidSize($size, $throw = false) { if (in_array($size, static::getSizes(), true)) { return true; } if ($throw) { throw new InvalidArgumentException("Unknown size '$size'."); } return false; }
php
{ "resource": "" }
q248597
Label.isValidFormat
validation
public static function isValidFormat($format, $throw = false) { if (in_array($format, static::getFormats(), true)) { return true; } if ($throw) { throw new InvalidArgumentException("Unknown format '$format'."); } return false; }
php
{ "resource": "" }
q248598
PaymentStates.isValidState
validation
static public function isValidState($state, $throwException = true) { if (in_array($state, static::getStates(), true)) { return true; } if ($throwException) { throw new InvalidArgumentException("Invalid payment states '$state'."); } return false; }
php
{ "resource": "" }
q248599
PriceTransformer.loadPriceMap
validation
private function loadPriceMap() { if (null === $this->pricesMap) { // Load price map only if price map is empty and not loaded $this->pricesMap = $this->getPricesMapLoader()->load($this->currency); } }
php
{ "resource": "" }