sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setRootAndPath(Document $root, $path) { Archive::set($this, 'root_and_path', array('root' => $root, 'path' => $path)); if (isset($this->data['embeddedsOne'])) { foreach ($this->data['embeddedsOne'] as $name => $embedded) { $embedded->setRootAndPath($root, $path.'.'.$name); } } if (isset($this->data['embeddedsMany'])) { foreach ($this->data['embeddedsMany'] as $name => $embedded) { $embedded->setRootAndPath($root, $path.'.'.$name); } } }
Set the root and path of the embedded document. @param \Mandango\Document\Document $root The root document. @param string $path The path. @api
entailment
public function isEmbeddedOneChangedInParent() { if (!$rap = $this->getRootAndPath()) { return false; } if ($rap['root'] instanceof EmbeddedGroup) { return false; } $exPath = explode('.', $rap['path']); unset($exPath[count($exPath) -1 ]); $parentDocument = $rap['root']; foreach ($exPath as $embedded) { $parentDocument = $parentDocument->{'get'.ucfirst($embedded)}(); if ($parentDocument instanceof EmbeddedGroup) { return false; } } $rap = $this->getRootAndPath(); $exPath = explode('.', $rap['path']); $name = $exPath[count($exPath) - 1]; return $parentDocument->isEmbeddedOneChanged($name); }
Returns if the embedded document is an embedded one document changed. @return bool If the document is an embedded one document changed.
entailment
public function getConnection() { if (!$this->connection) { if ($this->connectionName) { $this->connection = $this->mandango->getConnection($this->connectionName); } else { $this->connection = $this->mandango->getDefaultConnection(); } } return $this->connection; }
Returns the connection. @return \Mandango\ConnectionInterface The connection. @api
entailment
public function getCollection() { if (!$this->collection) { // gridfs if ($this->isFile) { $this->collection = $this->getConnection()->getMongoDB()->getGridFS($this->collectionName); // normal } else { $this->collection = $this->getConnection()->getMongoDB()->selectCollection($this->collectionName); } } return $this->collection; }
Returns the collection. @return \MongoCollection The collection. @api
entailment
public function createQuery(array $criteria = array()) { $class = $this->documentClass.'Query'; $query = new $class($this); $query->criteria($criteria); return $query; }
Create a query for the repository document class. @param array $criteria The criteria for the query (optional). @return Query The query. @api
entailment
public function idsToMongo(array $ids) { foreach ($ids as &$id) { $id = $this->idToMongo($id); } return $ids; }
Converts an array of ids to use in Mongo. @param array $ids An array of ids. @return array The array of ids converted.
entailment
public function findById(array $ids) { $mongoIds = $this->idsToMongo($ids); $cachedDocuments = $this->findCachedDocuments($mongoIds); if ($this->areAllDocumentsCached($cachedDocuments, $mongoIds)) { return $cachedDocuments; } $idsToQuery = $this->getIdsToQuery($cachedDocuments, $mongoIds); $queriedDocuments = $this->queryDocumentsByIds($idsToQuery); return array_merge($cachedDocuments, $queriedDocuments); }
Find documents by id. @param array $ids An array of ids. @return array An array of documents. @api
entailment
public function findOneById($id) { $id = $this->idToMongo($id); if ($this->identityMap->has($id)) { return $this->identityMap->get($id); } return $this->createQuery(array('_id' => $id))->one(); }
Returns one document by id. @param mixed $id An id. @return \Mandango\Document\Document|null The document or null if it does not exist. @api
entailment
public function update(array $query, array $newObject, array $options = array()) { return $this->getCollection()->update($query, $newObject, $options); }
Updates documents. @param array $query The query. @param array $newObject The new object. @param array $options The options for the update operation (optional). @return mixed The result of the update collection method.
entailment
public function group($keys, array $initial, $reduce, array $options = array()) { return $this->getCollection()->group($keys, $initial, $reduce, $options); }
Shortcut to the collection group method. @param mixed $keys The keys. @param array $initial The initial value. @param mixed $reduce The reduce function. @param array $options The options (optional). @return array The result @see \MongoCollection::group() @api
entailment
public function persist($documents) { if (!is_array($documents)) { $documents = array($documents); } foreach ($documents as $document) { $class = get_class($document); $oid = spl_object_hash($document); if (isset($this->remove[$class][$oid])) { unset($this->remove[$class][$oid]); } $this->persist[$class][$oid] = $document; } }
{@inheritdoc}
entailment
public function isPendingForPersist(Document $document) { return isset($this->persist[get_class($document)][spl_object_hash($document)]); }
Returns if a document is pending for persist. @param \Mandango\Document\Document A document. @return bool If the document is pending for persist. @api
entailment
public function isPendingForRemove(Document $document) { return isset($this->remove[get_class($document)][spl_object_hash($document)]); }
Returns if a document is pending for remove. @param \Mandango\Document\Document A document. @return bool If the document is pending for remove. @api
entailment
public function commit() { // execute foreach ($this->persist as $class => $documents) { $this->mandango->getRepository($class)->save($documents); } foreach ($this->remove as $class => $documents) { $this->mandango->getRepository($class)->delete($documents); } // clear $this->clear(); }
{@inheritdoc}
entailment
public function getFieldsCache() { $cache = $this->repository->getMandango()->getCache()->get($this->hash); return ($cache && isset($cache['fields'])) ? $cache['fields'] : null; }
Returns the fields in cache. @return array|null The fields in cache, or null if there is not.
entailment
public function mergeCriteria(array $criteria) { $this->criteria = null === $this->criteria ? $criteria : array_merge($this->criteria, $criteria); return $this; }
Merges a criteria with the current one. @param array $criteria The criteria. @return \Mandango\Query The query instance (fluent interface). @api
entailment
public function references($references) { if (null !== $references && !is_array($references)) { throw new \InvalidArgumentException(sprintf('The references "%s" are not valid.', $references)); } $this->references = $references; return $this; }
Set the references. @param array $references The references. @return \Mandango\Query The query instance (fluent interface). @throws \InvalidArgumentException If the references are not an array or null. @api
entailment
public function sort($sort) { if (null !== $sort && !is_array($sort)) { throw new \InvalidArgumentException(sprintf('The sort "%s" is not valid.', $sort)); } $this->sort = $sort; return $this; }
Set the sort. @param array|null $sort The sort. @return \Mandango\Query The query instance (fluent interface). @throws \InvalidArgumentException If the sort is not an array or null. @api
entailment
public function limit($limit) { if (null !== $limit) { if (!is_numeric($limit) || $limit != (int) $limit) { throw new \InvalidArgumentException('The limit is not valid.'); } $limit = (int) $limit; } $this->limit = $limit; return $this; }
Set the limit. @param int|null $limit The limit. @return \Mandango\Query The query instance (fluent interface). @throws \InvalidArgumentException If the limit is not a valid integer or null. @api
entailment
public function skip($skip) { if (null !== $skip) { if (!is_numeric($skip) || $skip != (int) $skip) { throw new \InvalidArgumentException('The skip is not valid.'); } $skip = (int) $skip; } $this->skip = $skip; return $this; }
Set the skip. @param int|null $skip The skip. @return \Mandango\Query The query instance (fluent interface). @throws \InvalidArgumentException If the skip is not a valid integer, or null. @api
entailment
public function batchSize($batchSize) { if (null !== $batchSize) { if (!is_numeric($batchSize) || $batchSize != (int) $batchSize) { throw new \InvalidArgumentException('The batchSize is not valid.'); } $batchSize = (int) $batchSize; } $this->batchSize = $batchSize; return $this; }
Set the batch size. @param int|null $batchSize The batch size. @return \Mandango\Query The query instance (fluent interface). @api
entailment
public function hint($hint) { if (null !== $hint && !is_array($hint)) { throw new \InvalidArgumentException(sprintf('The hint "%s" is not valid.', $hint)); } $this->hint = $hint; return $this; }
Set the hint. @param array|null The hint. @return \Mandango\Query The query instance (fluent interface). @api
entailment
public function slaveOkay($okay = true) { if (null !== $okay) { if (!is_bool($okay)) { throw new \InvalidArgumentException('The slave okay is not a boolean.'); } } $this->slaveOkay = $okay; return $this; }
Sets the slave okay. @param Boolean|null $okay If it is okay to query the slave (true by default). @return \Mandango\Query The query instance (fluent interface).
entailment
public function timeout($timeout) { if (null !== $timeout) { if (!is_numeric($timeout) || $timeout != (int) $timeout) { throw new \InvalidArgumentException('The timeout is not valid.'); } $timeout = (int) $timeout; } $this->timeout = $timeout; return $this; }
Set the timeout. @param int|null $timeout The timeout of the cursor. @return \Mandango\Query The query instance (fluent interface). @api
entailment
public function one() { $currentLimit = $this->limit; $results = $this->limit(1)->all(); $this->limit = $currentLimit; return $results ? array_shift($results) : null; }
Returns one result. @return \Mandango\Document\Document|null A document or null if there is no any result. @api
entailment
public function createCursor() { $cursor = $this->repository->getCollection()->find($this->criteria, $this->fields); if (null !== $this->sort) { $cursor->sort($this->sort); } if (null !== $this->limit) { $cursor->limit($this->limit); } if (null !== $this->skip) { $cursor->skip($this->skip); } if (null !== $this->batchSize) { $cursor->batchSize($this->batchSize); } if (null !== $this->hint) { $cursor->hint($this->hint); } if (null !== $this->slaveOkay) { $cursor->slaveOkay($this->slaveOkay); } if ($this->snapshot) { $cursor->snapshot(); } if (null !== $this->timeout) { $cursor->timeout($this->timeout); } return $cursor; }
Create a cursor with the data of the query. @return \MongoCursor A cursor with the data of the query.
entailment
public function stop() { $time = (int) round((microtime(true) - $this->time) * 1000); $this->time = null; return $time; }
Stop of count the time and returns the result. @return int The result.
entailment
public function setConnection($name, ConnectionInterface $connection) { if (null !== $this->loggerCallable) { $connection->setLoggerCallable($this->loggerCallable); $connection->setLogDefault(array('connection' => $name)); } else { $connection->setLoggerCallable(null); } $this->connections[$name] = $connection; }
Set a connection. @param string $name The connection name. @param ConnectionInterface $connection The connection. @api
entailment
public function setConnections(array $connections) { $this->connections = array(); foreach ($connections as $name => $connection) { $this->setConnection($name, $connection); } }
Set the connections. @param array $connections An array of connections. @api
entailment
public function removeConnection($name) { if (!$this->hasConnection($name)) { throw new \InvalidArgumentException(sprintf('The connection "%s" does not exists.', $name)); } unset($this->connections[$name]); }
Remove a connection. @param string $name The connection name. @throws \InvalidArgumentException If the connection does not exists. @api
entailment
public function getConnection($name) { if (!$this->hasConnection($name)) { throw new \InvalidArgumentException(sprintf('The connection "%s" does not exist.', $name)); } return $this->connections[$name]; }
Return a connection. @param string $name The connection name. @return ConnectionInterface The connection. @throws \InvalidArgumentException If the connection does not exists. @api
entailment
public function getDefaultConnection() { if (null === $this->defaultConnectionName) { throw new \RuntimeException('There is not default connection name.'); } if (!isset($this->connections[$this->defaultConnectionName])) { throw new \RuntimeException(sprintf('The default connection "%s" does not exists.', $this->defaultConnectionName)); } return $this->connections[$this->defaultConnectionName]; }
Returns the default connection. @return \Mandango\ConnectionInterface The default connection. @throws \RuntimeException If there is not default connection name. @throws \RuntimeException If the default connection does not exists. @api
entailment
public function getRepository($documentClass) { if (!isset($this->repositories[$documentClass])) { if (!$this->metadataFactory->hasClass($documentClass) || !$this->metadataFactory->isDocumentClass($documentClass)) { throw new \InvalidArgumentException(sprintf('The class "%s" is not a valid document class.', $documentClass)); } $repositoryClass = $documentClass.'Repository'; if (!class_exists($repositoryClass)) { throw new \RuntimeException(sprintf('The class "%s" does not exists.', $repositoryClass)); } $this->repositories[$documentClass] = new $repositoryClass($this); } return $this->repositories[$documentClass]; }
Returns repositories by document class. @param string $documentClass The document class. @return \Mandango\Repository The repository. @throws \InvalidArgumentException If the document class is not a valid document class. @throws \RuntimeException If the repository class build does not exist. @api
entailment
protected function doClassProcess() { $this->definitions['document_base']->addInterface('\ArrayAccess'); $this->processTemplate($this->definitions['document_base'], file_get_contents(__DIR__.'/templates/DocumentArrayAccess.php.twig')); }
{@inheritdoc}
entailment
public function findOne($query = array(), $fields = array()) { $cursor = new LoggableMongoCursor($this, $query, $fields, 'findOne'); $cursor->limit(-1); return $cursor->getNext(); }
findOne.
entailment
public function get($key) { $file = $this->dir.'/'.$key.'.php'; return file_exists($file) ? require($file) : null; }
{@inheritdoc}
entailment
public function set($key, $value) { if (!is_dir($this->dir) && false === @mkdir($this->dir, 0777, true)) { throw new \RuntimeException(sprintf('Unable to create the "%s" directory.', $this->dir)); } $file = $this->dir.'/'.$key.'.php'; $valueExport = var_export($value, true); $content = <<<EOF <?php return $valueExport; EOF; if (false === @file_put_contents($file, $content, LOCK_EX)) { throw new \RuntimeException(sprintf('Unable to write the "%s" file.', $file)); } }
{@inheritdoc}
entailment
public function remove($key) { $file = $this->dir.'/'.$key.'.php'; if (file_exists($file) && false === @unlink($file)) { throw new \RuntimeException(sprintf('Unable to remove the "%s" file.', $file)); } }
{@inheritdoc}
entailment
public function add($documents) { parent::add($documents); if ($rap = $this->getRootAndPath()) { foreach ($this->getAdd() as $key => $document) { $document->setRootAndPath($rap['root'], $rap['path'].'._add'.$key); } } }
{@inheritdoc}
entailment
protected function doInitializeSavedData() { $data = $this->getSavedData(); if ($data !== null) { return $data; } $rap = $this->getRootAndPath(); if ($rap['root']->isNew()) { return array(); } $rap['root']->addFieldCache($rap['path']); $result = $rap['root'] ->getRepository() ->getCollection() ->findOne(array('_id' => $rap['root']->getId()), array($rap['path'])) ; return ($result && isset($result[$rap['path']])) ? $result[$rap['path']] : array(); }
{@inheritdoc}
entailment
protected function doInitializeSaved(array $data) { $documentClass = $this->getDocumentClass(); $rap = $this->getRootAndPath(); $mandango = $rap['root']->getMandango(); $saved = array(); foreach ($data as $key => $datum) { $saved[] = $document = new $documentClass($mandango); $document->setDocumentData($datum); $document->setRootAndPath($rap['root'], $rap['path'].'.'.$key); } return $saved; }
{@inheritdoc}
entailment
protected function doInitializeSaved(array $data) { return $this->getParent()->getMandango()->getRepository($this->getDocumentClass())->findById($data); }
{@inheritdoc}
entailment
public function createQuery() { return $this->getParent()->getMandango()->getRepository($this->getDocumentClass())->createQuery(array( '_id' => array('$in' => $this->doInitializeSavedData()), )); }
Creates and returns a query to query the referenced elements. @api
entailment
public function getCode(array $options) { $increment = isset($options['increment']) ? $options['increment'] : 1; $start = isset($options['start']) ? $options['start'] : null; // increment if (!is_int($increment) || 0 === $increment) { throw new \InvalidArgumentException('The option "increment" must be an integer distinct of 0.'); } // start if (null === $start) { $start = $increment > 0 ? 1 : -1; } elseif (!is_int($start) || 0 === $start) { throw new \InvalidArgumentException('The option "start" must be an integer distinct of 0.'); } return <<<EOF \$serverInfo = \$repository->getConnection()->getMongo()->selectDB('admin')->command(array('buildinfo' => true)); \$mongoVersion = \$serverInfo['version']; \$commandResult = \$repository->getConnection()->getMongoDB()->command(array( 'findandmodify' => 'mandango_sequence_id_generator', 'query' => array('_id' => \$repository->getCollectionName()), 'update' => array('\$inc' => array('sequence' => $increment)), 'new' => true, )); if ( (version_compare(\$mongoVersion, '2.0', '<') && \$commandResult['ok']) || (version_compare(\$mongoVersion, '2.0', '>=') && null !== \$commandResult['value']) ) { %id% = \$commandResult['value']['sequence']; } else { \$repository ->getConnection() ->getMongoDB() ->selectCollection('mandango_sequence_id_generator') ->insert(array('_id' => \$repository->getCollectionName(), 'sequence' => $start) ); %id% = $start; } EOF; }
{@inheritdoc}
entailment
public function setLoggerCallable($loggerCallable = null) { if (null !== $this->mongo) { throw new \RuntimeException('The connection has already Mongo.'); } $this->loggerCallable = $loggerCallable; }
{@inheritdoc}
entailment
public function getMongo() { if (null === $this->mongo) { if (null !== $this->loggerCallable) { $this->mongo = new \Mandango\Logger\LoggableMongo($this->server, $this->options); $this->mongo->setLoggerCallable($this->loggerCallable); if (null !== $this->logDefault) { $this->mongo->setLogDefault($this->logDefault); } } else { $this->mongo = new \Mongo($this->server, $this->options); } } return $this->mongo; }
{@inheritdoc}
entailment
public function getMongoDB() { if (null === $this->mongoDB) { $this->mongoDB = $this->getMongo()->selectDB($this->dbName); } return $this->mongoDB; }
{@inheritdoc}
entailment
protected function doInitializeSaved(array $data) { $parent = $this->getParent(); $mandango = $parent->getMandango(); $discriminatorField = $this->getDiscriminatorField(); $discriminatorMap = $this->getDiscriminatorMap(); $ids = array(); foreach ($data as $datum) { if ($discriminatorMap) { $documentClass = $discriminatorMap[$datum[$discriminatorField]]; } else { $documentClass = $datum[$discriminatorField]; } $ids[$documentClass][] = $datum['id']; } $documents = array(); foreach ($ids as $documentClass => $documentClassIds) { foreach ((array) $mandango->getRepository($documentClass)->findById($documentClassIds) as $document) { $documents[] = $document; } } return $documents; }
{@inheritdoc}
entailment
public function add($documents) { if (!is_array($documents)) { $documents = array($documents); } $add =& Archive::getByRef($this, 'add', array()); foreach ($documents as $document) { $add[] = $document; } }
Adds document/s to the add queue of the group. @param \Mandango\Document\AbstractDocument|array $documents One or more documents. @api
entailment
public function remove($documents) { if (!is_array($documents)) { $documents = array($documents); } $remove =& Archive::getByRef($this, 'remove', array()); foreach ($documents as $document) { $remove[] = $document; } }
Adds document/s to the remove queue of the group. @param \Mandango\Document\AbstractDocument|array $documents One of more documents. @api
entailment
public function all() { $documents = array_merge($this->getSaved(), $this->getAdd()); foreach ($this->getRemove() as $document) { if (false !== $key = array_search($document, $documents)) { unset($documents[$key]); } } return array_values($documents); }
Returns the saved + add - removed elements. @api
entailment
public function replace(array $documents) { $this->clearAdd(); $this->clearRemove(); $this->remove($this->getSaved()); $this->add($documents); }
Replace all documents. @param array $documents An array of documents. @api
entailment
public function reset() { if ($this->getAdd() || $this->getRemove()) { $this->clearSaved(); } $this->clearAdd(); $this->clearRemove(); }
Resets the group (clear adds and removed, and saved if there are adds or removed). @api
entailment
public function createCollection($name, $capped = false, $size = 0, $max = 0) { $this->time->start(); $return = parent::createCollection($name, $capped, $size, $max); $time = $this->time->stop(); $this->log(array( 'type' => 'createCollection', 'name' => $name, 'capped' => $capped, 'size' => $size, 'max' => $max, 'time' => $time, )); return $return; }
createCollection.
entailment
public function createDBRef($collection, $a) { $this->time->start(); $return = parent::createDBRef($collection, $a); $time = $this->time->stop(); $this->log(array( 'type' => 'createDBRef', 'collection' => $collection, 'a' => $a, 'time' => $time, )); return $return; }
createDbRef.
entailment
public function execute($code, array $args = array()) { $this->time->start(); $return = parent::execute($code, $args); $time = $this->time->stop(); $this->log(array( 'type' => 'execute', 'code' => $code, 'args' => $args, 'time' => $time, )); return $return; }
execute.
entailment
public function listCollections($includeSystemCollections = false) { $this->time->start(); $return = parent::listCollections($includeSystemCollections); $time = $this->time->stop(); $this->log(array( 'type' => 'listCollections', 'time' => $time, )); return $return; }
listCollections.
entailment
public function toMongo($value) { if (is_file($value)) { $value = file_get_contents($value); } return new \MongoBinData($value, \MongoBinData::BYTE_ARRAY); }
{@inheritdoc}
entailment
public function addError($errorCode) { $this->errors[] = $errorCode; if (!array_key_exists('Errors', $this->attributes)) { $this->attributes['Errors'] = ''; } return $this; }
@param $errorCode @return $this
entailment
public static function isValidValue($value, $strict = false) { $values = self::getConstantValues(); return in_array($value, $values, $strict); }
@param $value @param bool $strict @return bool
entailment
public function calculate($price, $unitTax, $quantity = 0) { $this->Tax = $unitTax * $quantity; $this->Total = $this->Tax + ($quantity * $price); return $this; }
Used to set the line item's values so that the total and tax add up correctly. @param int $price @param int $unitTax @param int $quantity @return $this
entailment
public function setItemsAttribute($items) { if (!is_array($items)) { throw new \InvalidArgumentException('Items must be an array'); } foreach ($items as $key => $item) { if (!($item instanceof Item)) { $items[$key] = new Item($item); } } $this->attributes['Items'] = $items; return $this; }
@param array $items @return $this
entailment
public function setShippingMethodAttribute($shippingMethod) { if (null === $shippingMethod) { $this->attributes['ShippingMethod'] = ShippingMethod::UNKNOWN; } else { $this->validateEnum('Eway\Rapid\Enum\ShippingMethod', 'ShippingMethod', $shippingMethod); } return $this; }
@param string $shippingMethod @return $this
entailment
public function getTransaction($reference) { if (empty($reference)) { throw new InvalidArgumentException(); } return $this->getRequest([ self::API_TRANSACTION_QUERY, ['Reference' => $reference] ]); }
@param $reference @return ResponseInterface
entailment
public function getTransactionInvoiceNumber($invoiceNumber) { if (empty($invoiceNumber)) { throw new InvalidArgumentException(); } return $this->getRequest([ self::API_TRANSACTION_INVOICE_NUMBER_QUERY, ['InvoiceNumber' => $invoiceNumber] ]); }
@param $invoiceNumber @return ResponseInterface
entailment
public function getTransactionInvoiceReference($invoiceReference) { if (empty($invoiceReference)) { throw new InvalidArgumentException(); } return $this->getRequest([ self::API_TRANSACTION_INVOICE_REFERENCE_QUERY, ['InvoiceReference' => $invoiceReference] ]); }
@param $invoiceReference @return ResponseInterface
entailment
public function getAccessCode($accessCode) { if (empty($accessCode)) { throw new InvalidArgumentException(); } return $this->getRequest([ self::API_ACCESS_CODE_QUERY, ['AccessCode' => $accessCode] ]); }
@param $accessCode @return ResponseInterface
entailment
public function getCustomer($tokenCustomerId) { if (empty($tokenCustomerId)) { throw new InvalidArgumentException(); } return $this->getRequest([ self::API_CUSTOMER_QUERY, ['TokenCustomerID' => $tokenCustomerId] ]); }
@param $tokenCustomerId @return ResponseInterface
entailment
public function getUri($uri, $withBaseUrl = true) { $baseUrl = $withBaseUrl ? $this->baseUrl : ''; if (!is_array($uri)) { return $baseUrl.$uri; } list($uri, $vars) = $uri; $uri = $baseUrl.$uri; if (!is_array($vars)) { throw new InvalidArgumentException(); } foreach ($vars as $key => $value) { $uri = str_replace('{'.$key.'}', $value, $uri); } return $uri; }
@param $uri @param bool $withBaseUrl @return mixed
entailment
private function request($method, $uri, $data = []) { $uri = $this->getUri($uri); $headers = []; // Basic Auth $credentials = $this->key.':'.$this->password; // User Agent $agent = sprintf("%s %s", Client::NAME, Client::VERSION); $ch = curl_init(); if (strtoupper($method) === 'GET' && !empty($data)) { $queryString = http_build_query($data); $uri .= '?'.$queryString; } $options = [ CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_USERAGENT => $agent, CURLOPT_USERPWD => $credentials, CURLOPT_TIMEOUT => 60, ]; if (strtoupper($method) === 'POST') { $jsonData = json_encode($data); $headers[] = 'Content-Type: application/json'; $headers[] = 'Content-Length: '.strlen($jsonData); $options[CURLOPT_CUSTOMREQUEST] = 'POST'; $options[CURLOPT_POSTFIELDS] = $jsonData; } if (isset($this->version) && is_numeric($this->version)) { $headers[] = 'X-EWAY-APIVERSION: '.$this->version; } $options[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $options); $rawResponse = curl_exec($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); if (curl_errno($ch)) { $responseError = curl_error($ch); $responseBody = ''; } else { $responseError = ''; $responseBody = $this->parseResponse($rawResponse, $headerSize); } $response = new Response($statusCode, $responseBody, $responseError); curl_close($ch); return $response; }
@param string $method @param string $uri @param array $data @return ResponseInterface
entailment
private function parseResponse($rawResponse, $headerSize) { foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) { if (stripos($rawResponse, $established_header) !== false) { $rawResponse = str_ireplace($established_header, '', $rawResponse); // Older cURL versions did not account for proxy headers in the // header size if (!$this->needsCurlProxyFix()) { $headerSize -= strlen($established_header); } break; } } $responseBody = substr($rawResponse, $headerSize); return $responseBody; }
Returns the HTTP body from raw response. @param string $rawResponse @param string $headerSize @return string
entailment
public function setTransactionsAttribute($transactions) { if (!is_array($transactions)) { throw new \InvalidArgumentException('Transactions must be an array'); } foreach ($transactions as $key => $transaction) { if (!($transaction instanceof Transaction)) { $transactions[$key] = new Transaction($transaction); } } $this->attributes['Transactions'] = $transactions; return $this; }
@param array $transactions @return $this
entailment
private function doRefund($refund) { /** @var Refund $refund */ $refund = ClassValidator::getInstance('Eway\Rapid\Model\Refund', $refund); return $this->getHttpService()->postTransactionRefund($refund->Refund->TransactionID, $refund->toArray()); }
@param $refund @return ResponseInterface
entailment
private function doCancelTransaction($transactionId) { $refund = [ 'TransactionID' => $transactionId, ]; /** @var Refund $refund */ $refund = ClassValidator::getInstance('Eway\Rapid\Model\Refund', $refund); return $this->getHttpService()->postCancelAuthorisation($refund->toArray()); }
@param $transactionId @return ResponseInterface
entailment
private function doSettlementSearch($query) { $search = ClassValidator::getInstance('Eway\Rapid\Model\SettlementSearch', $query); return $this->getHttpService()->getSettlementSearch($search->toArray()); }
@param $query @return ResponseInterface
entailment
private function invoke($responseClass) { if (!$this->isValid()) { return $this->getErrorResponse($responseClass); } try { $caller = $this->getCaller(); $response = call_user_func_array([$this, 'do'.ucfirst($caller['function'])], $caller['args']); return $this->wrapResponse($responseClass, $response); } catch (InvalidArgumentException $e) { $this->addError(self::ERROR_INVALID_ARGUMENT); } catch (MassAssignmentException $e) { $this->addError(self::ERROR_INVALID_ARGUMENT); } return $this->getErrorResponse($responseClass); }
@param $responseClass @return AbstractResponse
entailment
private function wrapResponse($class, $httpResponse = null) { $data = []; try { if (isset($httpResponse)) { $this->checkResponse($httpResponse); $body = (string)$httpResponse->getBody(); if (!$this->isJson($body)) { $this->log('error', "Response is not valid JSON"); $this->addError(self::ERROR_INVALID_JSON); } else { $data = json_decode($body, true); } } else { $this->log('error', "Response from gateway is empty"); $this->addError(self::ERROR_EMPTY_RESPONSE); } } catch (RequestException $e) { // An error code is already provided by checkResponse } /** @var AbstractResponse $response */ $response = new $class($data); foreach ($this->getErrors() as $errorCode) { $response->addError($errorCode); } return $response; }
@param string $class @param ResponseInterface $httpResponse @return mixed
entailment
private function addError($errorCode, $valid = true) { $this->isValid = $valid; $this->errors[] = $errorCode; return $this; }
@param string $errorCode @return $this
entailment
private function checkResponse($response) { $hasRequestError = false; if (preg_match('/4\d\d/', $response->getStatusCode())) { $this->log('error', "Invalid API key or password"); $this->addError(self::ERROR_HTTP_AUTHENTICATION_ERROR, false); $hasRequestError = true; } elseif (preg_match('/5\d\d/', $response->getStatusCode())) { $this->log('error', "Gateway error - HTTP " . $response->getStatusCode()); $this->addError(self::ERROR_HTTP_SERVER_ERROR); $hasRequestError = true; } elseif ($response->getError()) { $this->log('error', "Connection error: " . $response->getError()); $this->addError(self::ERROR_CONNECTION_ERROR); $hasRequestError = true; } if ($hasRequestError) { throw new RequestException(sprintf("Last HTTP response status code: %s", $response->getStatusCode())); } }
@param ResponseInterface $response @throws RequestException
entailment
private function customerToTransaction($customer) { $transaction = [ 'Customer' => $customer->toArray(), 'TransactionType' => TransactionType::MOTO, ]; foreach ($customer->toArray() as $key => $value) { if ($key != 'TokenCustomerID') { $transaction[$key] = $value; } } /** @var Transaction $transaction */ return ClassValidator::getInstance('Eway\Rapid\Model\Transaction', $transaction); }
Convert a Customer to a Transaction object for a create or update token transaction @param Eway\Rapid\Model\Customer $customer @return Eway\Rapid\Model\Transaction
entailment
public function setCustomersAttribute($customers) { if (!is_array($customers)) { throw new \InvalidArgumentException('Customers must be an array'); } foreach ($customers as $key => $customer) { if (!($customer instanceof Customer)) { $customers[$key] = new Customer($customer); } } $this->attributes['Customers'] = $customers; return $this; }
@param array $customers @return $this
entailment
public function log($level, $message, array $context = array()) { if (!LogLevel::isValidValue($level)) { throw new \InvalidArgumentException('Invalid loge level: '.$level); } $timestamp = time(); $log = sprintf( '[%s] %s %s', date('Y-m-d H:i:s', $timestamp), strtoupper($level), self::interpolate($message, $context) ); error_log($log); }
Logs with an arbitrary level. This logs to PHP's error log. @param mixed $level @param string $message @param array $context @return null
entailment
private function interpolate($message, array $context = array()) { $replaces = array(); foreach ($context as $key => $val) { if (is_bool($val)) { $val = '[bool: ' . (int) $val . ']'; } elseif (is_null($val) || is_scalar($val) || ( is_object($val) && method_exists($val, '__toString') ) ) { $val = (string) $val; } elseif (is_array($val) || is_object($val)) { $val = @json_encode($val); } else { $val = '[type: ' . gettype($val) . ']'; } $replaces['{' . $key . '}'] = $val; } return strtr($message, $replaces); }
Interpolates context values into the message placeholders.
entailment
public static function validate($class, $field, $value) { $abstractEnum = 'Eway\Rapid\Enum\AbstractEnum'; if (!is_subclass_of($class, $abstractEnum)) { throw new InvalidArgumentException(sprintf('%s must extends %s', $class, $abstractEnum)); } if (!call_user_func($class.'::isValidValue', $value, true)) { throw new InvalidArgumentException(call_user_func($class.'::getValidationMessage', $field)); } return $value; }
@param $class @param $field @param $value @return mixed @throws InvalidArgumentException
entailment
public static function createClient($apiKey, $apiPassword, $endpoint = ClientContract::MODE_SANDBOX, $logger = null) { return new Client($apiKey, $apiPassword, $endpoint, $logger); }
Static method to create a new Rapid Client object configured to communicate with a specific instance of the Rapid API. @param string $apiKey eWAY Rapid API key @param string $apiPassword eWAY Rapid API password @param string $endpoint eWAY Rapid API endpoint - one of 'Sandbox' or 'Production' @param Psr\Log\LoggerInterface $logger PSR-3 logger @return ClientContract an eWAY Rapid Client
entailment
public static function getMessage($errorCode, $language = 'en') { self::initMessages(); $messagesByLanguage = self::getMessagesByLanguage($language); if (!array_key_exists($errorCode, $messagesByLanguage)) { return $errorCode; } return $messagesByLanguage[$errorCode]; }
This static method provides a message suitable for display to a user corresponding to a given Rapid Code & language. @param string $errorCode @param string $language 2 character language code, defaults to en @return string
entailment
private static function getMessagesByLanguage($language) { $messages = []; if (!array_key_exists($language, self::$messages)) { self::tryLoadingMessageFile($language); } if (array_key_exists($language, self::$messages)) { $messages = self::$messages[$language]; } else { self::tryLoadingMessageFile('en'); if (array_key_exists('en', self::$messages)) { $messages = self::$messages['en']; } } return $messages; }
@param string $language @return array
entailment
public static function decode($bytes, $connection) { $masked = ord($bytes[1]) >> 7; $data_length = $masked ? ord($bytes[1]) & 127 : ord($bytes[1]); $decoded_data = ''; if ($masked === true) { if ($data_length === 126) { $mask = substr($bytes, 4, 4); $coded_data = substr($bytes, 8); } else if ($data_length === 127) { $mask = substr($bytes, 10, 4); $coded_data = substr($bytes, 14); } else { $mask = substr($bytes, 2, 4); $coded_data = substr($bytes, 6); } for ($i = 0; $i < strlen($coded_data); $i++) { $decoded_data .= $coded_data[$i] ^ $mask[$i % 4]; } } else { if ($data_length === 126) { $decoded_data = substr($bytes, 4); } else if ($data_length === 127) { $decoded_data = substr($bytes, 10); } else { $decoded_data = substr($bytes, 2); } } if ($connection->websocketCurrentFrameLength) { $connection->websocketDataBuffer .= $decoded_data; return $connection->websocketDataBuffer; } else { if ($connection->websocketDataBuffer !== '') { $decoded_data = $connection->websocketDataBuffer . $decoded_data; $connection->websocketDataBuffer = ''; } return $decoded_data; } }
Websocket decode. @param string $buffer @param ConnectionInterface $connection @return string
entailment
public function batchQueries(array $queries) { /* * Set the client to use batch mode * When batch mode is activated calls to Analytics::query will return * the request object instead of the resulting data */ $this->client->setUseBatch(true); $batch = new \Google_Http_Batch($this->client); foreach ($queries as $query) { // pull the key from the array if specified so we can later identify our result $key = array_pull($query, 'key'); // call the original query method to get the request object $req = call_user_func_array(__NAMESPACE__ .'\Analytics::query' ,$query); $batch->add($req, $key); } $results = $batch->execute(); // Set the client back to normal mode $this->client->setUseBatch(false); return $results; }
Runs analytics query calls in batch mode It accepts an array of queries as specified by the parameters of the Analytics::query function With an additional optional parameter named key, which is used to identify the results for a specific object Returns an array with object keys as response-KEY where KEY is the key you specified or a random key returned from analytics. @param array $queries @return array|null
entailment
public static function loadByNamespace($name) { // 相对路径 $class_path = str_replace('\\', DIRECTORY_SEPARATOR ,$name); // 如果是Workerman命名空间,则在当前目录寻找类文件 if(strpos($name, 'Workerman\\') === 0) { $class_file = __DIR__.substr($class_path, strlen('Workerman')).'.php'; } else { // 先尝试在应用目录寻找文件 if(self::$_appInitPath) { $class_file = self::$_appInitPath . DIRECTORY_SEPARATOR . $class_path.'.php'; } // 文件不存在,则在上一层目录寻找 if(empty($class_file) || !is_file($class_file)) { $class_file = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR . "$class_path.php"; } } // 找到文件 if(is_file($class_file)) { // 加载 require_once($class_file); if(class_exists($name, false)) { return true; } } return false; }
根据命名空间加载文件 @param string $name @return boolean
entailment
public function close($data = null, $raw = false) { if ($data !== null) { $this->send($data, $raw); } Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ); fclose($this->_socket); return true; }
Close connection. @param mixed $data @return bool
entailment
public function reConnect($after = 0) { $this->_status = self::STATUS_INITIAL; if ($this->_reconnectTimer) { Timer::del($this->_reconnectTimer); } if ($after > 0) { $this->_reconnectTimer = Timer::add($after, array($this, 'connect'), null, false); return; } $this->connect(); }
Reconnect. @param int $after @return void
entailment
public function checkConnection($socket) { // Remove EV_EXPECT for windows. if(DIRECTORY_SEPARATOR === '\\') { Worker::$globalEvent->del($socket, EventInterface::EV_EXCEPT); } // Check socket state. if ($address = stream_socket_get_name($socket, true)) { // Remove write listener. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE); // Nonblocking. stream_set_blocking($socket, 0); // Compatible with hhvm if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($socket, 0); } // Try to open keepalive for tcp and disable Nagle algorithm. if (function_exists('socket_import_stream') && $this->transport === 'tcp') { $raw_socket = socket_import_stream($socket); socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1); socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1); } // Register a listener waiting read event. Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead')); // There are some data waiting to send. if ($this->_sendBuffer) { Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite')); } $this->_status = self::STATUS_ESTABLISHED; $this->_remoteAddress = $address; $this->_sslHandshakeCompleted = true; // Try to emit onConnect callback. if ($this->onConnect) { try { call_user_func($this->onConnect, $this); } catch (\Exception $e) { Worker::log($e); exit(250); } catch (\Error $e) { Worker::log($e); exit(250); } } // Try to emit protocol::onConnect if (method_exists($this->protocol, 'onConnect')) { try { call_user_func(array($this->protocol, 'onConnect'), $this); } catch (\Exception $e) { Worker::log($e); exit(250); } catch (\Error $e) { Worker::log($e); exit(250); } } } else { // Connection failed. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(microtime(true) - $this->_connectStartTime, 4) . ' seconds'); if ($this->_status === self::STATUS_CLOSING) { $this->destroy(); } if ($this->_status === self::STATUS_CLOSED) { $this->onConnect = null; } } }
Check connection is successfully established or faild. @param resource $socket @return void
entailment
public function register() { $this->app->bind('Thujohn\Analytics\Analytics', function ($app) { if(!\File::exists($app['config']->get('analytics::certificate_path'))) { throw new \Exception("Can't find the .p12 certificate in: " . $app['config']->get('analytics::certificate_path')); } $config = array( 'oauth2_client_id' => $app['config']->get('analytics::client_id'), 'use_objects' => $app['config']->get('analytics::use_objects'), ); $client = new \Google_Client($config); $client->setAccessType('offline'); $client->setAssertionCredentials( new \Google_Auth_AssertionCredentials( $app['config']->get('analytics::service_email'), array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($app['config']->get('analytics::certificate_path')) ) ); return new Analytics($client); }); $this->app->singleton('analytics', 'Thujohn\Analytics\Analytics'); }
Register the service provider. @return void
entailment
public function close($data = null, $raw = false) { if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) { return; } else { if ($data !== null) { $this->send($data, $raw); } $this->_status = self::STATUS_CLOSING; } if ($this->_sendBuffer === '') { $this->destroy(); } }
Close connection. @param mixed $data @param bool $raw @return void
entailment
public static function init() { if(strpos(strtolower(PHP_OS), 'win') !== 0) { exit("workerman-for-win can not run in linux\n"); } if (false !== strpos(ini_get('disable_functions'), 'proc_open')) { exit("\r\nWarning: proc_open() has been disabled for security reasons. \r\n\r\nSee http://wiki.workerman.net/Error5\r\n"); } $backtrace = debug_backtrace(); static::$_startFile = $backtrace[count($backtrace)-1]['file']; // 没有设置日志文件,则生成一个默认值 if(empty(static::$logFile)) { static::$logFile = __DIR__ . '/../workerman.log'; } // 标记状态为启动中 static::$_status = static::STATUS_STARTING; $event_loop_class = static::getEventLoopName(); static::$globalEvent = new $event_loop_class; Timer::init(static::$globalEvent); }
初始化一些环境变量 @return void
entailment
protected static function initWorkers() { foreach(static::$_workers as $worker) { // 没有设置worker名称,则使用none代替 if(empty($worker->name)) { $worker->name = 'none'; } // 获得所有worker名称中最大长度 $worker_name_length = strlen($worker->name); if(static::$_maxWorkerNameLength < $worker_name_length) { static::$_maxWorkerNameLength = $worker_name_length; } // 获得所有_socketName中最大长度 $socket_name_length = strlen($worker->getSocketName()); if(static::$_maxSocketNameLength < $socket_name_length) { static::$_maxSocketNameLength = $socket_name_length; } $user_name_length = strlen($worker->user); if(static::$_maxUserNameLength < $user_name_length) { static::$_maxUserNameLength = $user_name_length; } } }
初始化所有的worker实例,主要工作为获得格式化所需数据及监听端口 @return void
entailment
public static function runAllWorkers() { // 只有一个start文件时执行run if(count(static::$_startFiles) === 1) { // win不支持同一个页面执初始化多个worker if(count(static::$_workers) > 1) { echo "@@@ Error: multi workers init in one php file are not support @@@\r\n"; echo "@@@ Please visit http://wiki.workerman.net/Multi_woker_for_win @@@\r\n"; } elseif(count(static::$_workers) <= 0) { exit("@@@no worker inited@@@\r\n\r\n"); } // 执行worker的run方法 reset(static::$_workers); $worker = current(static::$_workers); $worker->listen(); // 子进程阻塞在这里 $worker->run(); exit("@@@child exit@@@\r\n"); } // 多个start文件则多进程打开 elseif(count(static::$_startFiles) > 1) { static::$globalEvent = new Select(); Timer::init(static::$globalEvent); foreach(static::$_startFiles as $start_file) { static::openProcess($start_file); } } // 没有start文件提示错误 else { //exit("@@@no worker inited@@@\r\n"); } }
运行所有的worker
entailment
public static function openProcess($start_file) { // 保存子进程的输出 $start_file = realpath($start_file); $std_file = sys_get_temp_dir() . '/'.str_replace(array('/', "\\", ':'), '_', $start_file).'.out.txt'; // 将stdou stderr 重定向到文件 $descriptorspec = array( 0 => array('pipe', 'a'), // stdin 1 => array('file', $std_file, 'w'), // stdout 2 => array('file', $std_file, 'w') // stderr ); // 保存stdin句柄,用来探测子进程是否关闭 $pipes = array(); // 打开子进程 $process= proc_open("php \"$start_file\" -q", $descriptorspec, $pipes); // 打开stdout stderr 文件句柄 $std_handler = fopen($std_file, 'a+'); // 非阻塞 stream_set_blocking($std_handler, 0); // 定时读取子进程的stdout stderr $timer_id = Timer::add(0.1, function()use($std_handler) { echo fread($std_handler, 65535); }); // 保存子进程句柄 static::$_process[$start_file] = array($process, $start_file, $timer_id); }
打开一个子进程 @param string $start_file
entailment
protected static function displayUI() { global $argv; // -q不打印 if(in_array('-q', $argv)) { return; } echo "----------------------- WORKERMAN -----------------------------\n"; echo 'Workerman version:' . Worker::VERSION . " PHP version:".PHP_VERSION."\n"; echo "------------------------ WORKERS -------------------------------\n"; echo "worker",str_pad('', static::$_maxWorkerNameLength+2-strlen('worker')), "listen",str_pad('', static::$_maxSocketNameLength+2-strlen('listen')), "processes ","status\n"; foreach(static::$_workers as $worker) { echo str_pad($worker->name, static::$_maxWorkerNameLength+2),str_pad($worker->getSocketName(), static::$_maxSocketNameLength+2), str_pad(' '.$worker->count, 9), " [OK] \n";; } echo "----------------------------------------------------------------\n"; echo "Press Ctrl-C to quit. Start success.\n"; }
展示启动界面 @return void
entailment