sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setSubscriptionId($subscriptionId) { if (strlen($subscriptionId) > 50) { throw new InvalidArgumentException("Subscription id cannot be longer than 50 characters"); } if (preg_match('/[^a-zA-Z0-9_-]/', $subscriptionId)) { throw new InvalidArgumentException("Subscription id cannot contain special characters"); } $this->parameters['subscription_id'] = $subscriptionId; }
Unique identifier of the subscription. The subscription id must be assigned dynamically. @author René de Kat <[email protected]> @param string $subscriptionId (maxlength 50)
entailment
public function setSubscriptionAmount($amount) { if (!is_int($amount)) { throw new InvalidArgumentException("Integer expected. Amount is always in cents"); } if ($amount <= 0) { throw new InvalidArgumentException("Amount must be a positive number"); } if ($amount >= 1.0E+15) { throw new InvalidArgumentException("Amount is too high"); } $this->parameters['sub_amount'] = $amount; }
Amount of the subscription (can be different from the amount of the original transaction) multiplied by 100, since the format of the amount must not contain any decimals or other separators. @author René de Kat <[email protected]> @param integer $amount
entailment
public function setSubscriptionDescription($description) { if (strlen($description) > 100) { throw new InvalidArgumentException("Subscription description cannot be longer than 100 characters"); } if (preg_match('/[^a-zA-Z0-9_ -]/', $description)) { throw new InvalidArgumentException("Subscription description cannot contain special characters"); } $this->parameters['sub_com'] = $description; }
Order description @author René de Kat <[email protected]> @param string $description (maxlength 100)
entailment
public function setSubscriptionOrderId($orderId) { if (strlen($orderId) > 40) { throw new InvalidArgumentException("Subscription order id cannot be longer than 40 characters"); } if (preg_match('/[^a-zA-Z0-9_-]/', $orderId)) { throw new InvalidArgumentException("Subscription order id cannot contain special characters"); } $this->parameters['sub_orderid'] = $orderId; }
OrderID for subscription payments @author René de Kat <[email protected]> @param string $orderId (maxlength 40)
entailment
public function setSubscriptionPeriod(SubscriptionPeriod $period) { $this->parameters['sub_period_unit'] = $period->getUnit(); $this->parameters['sub_period_number'] = $period->getInterval(); $this->parameters['sub_period_moment'] = $period->getMoment(); }
Set subscription payment interval @author René de Kat <[email protected]>
entailment
public function setSubscriptionComment($comment) { if (strlen($comment) > 200) { throw new InvalidArgumentException("Subscription comment cannot be longer than 200 characters"); } if (preg_match('/[^a-zA-Z0-9_ -]/', $comment)) { throw new InvalidArgumentException("Subscription comment cannot contain special characters"); } $this->parameters['sub_comment'] = $comment; }
Set comment for merchant @author René de Kat <[email protected]> @param string $comment
entailment
public function decorate(IndexMetadataInterface $indexMetadata, $object, Document $document) { $indexName = $this->decorator->decorate($indexMetadata, $object, $document); return $this->prefix . '_' . $indexName; }
{@inheritdoc}
entailment
public function undecorate($decoratedIndexName) { $decoratedIndexName = $this->removePrefix($decoratedIndexName); return $this->decorator->undecorate($decoratedIndexName); }
{@inheritdoc}
entailment
public function isVariant($indexName, $decoratedIndexName, array $options = []) { if (($indexName === $decoratedIndexName && $this->prefix) || 0 !== strpos($decoratedIndexName, $this->prefix)) { // if both names are the same, and a prefix is set the name was not decorated by this decorator return false; } $undecoratedIndexName = $this->removePrefix($decoratedIndexName); if (!$this->decorator->isVariant($indexName, $undecoratedIndexName, $options)) { return false; } return $indexName === $this->decorator->undecorate($undecoratedIndexName); }
{@inheritdoc}
entailment
private function removePrefix($decoratedIndexName) { if (0 === strpos($decoratedIndexName, $this->prefix . '_')) { $decoratedIndexName = substr($decoratedIndexName, strlen($this->prefix) + 1); return $decoratedIndexName; } return $decoratedIndexName; }
Removes the prefix added by this decorator from the index name. @param $decoratedIndexName @return string
entailment
public function getMetadataForObject($object) { foreach ($this->providers as $provider) { $metadata = $provider->getMetadataForObject($object); if (null !== $metadata) { return $metadata; } } return; }
{@inheritdoc}
entailment
public function getAllMetadata() { $metadatas = []; foreach ($this->providers as $provider) { foreach ($provider->getAllMetadata() as $metadata) { $metadatas[] = $metadata; } } return $metadatas; }
{@inheritdoc}
entailment
public function getMetadataForDocument(Document $document) { foreach ($this->providers as $provider) { $metadata = $provider->getMetadataForDocument($document); if (null !== $metadata) { return $metadata; } } return; }
{@inheritdoc}
entailment
public function index(Document $document, $indexName) { $index = $this->getLuceneIndex($indexName); // check to see if the subject already exists $this->removeExisting($index, $document); $luceneDocument = new Lucene\Document(); $aggregateValues = []; foreach ($document->getFields() as $field) { $type = $field->getType(); $value = $field->getValue(); if (Field::TYPE_NULL === $type) { continue; } // Zend Lucene does not support "types". We should allow other "types" once they // are properly implemented in at least one other adapter. if (Field::TYPE_STRING !== $type && Field::TYPE_ARRAY !== $type) { throw new \InvalidArgumentException( sprintf( 'Search field type "%s" is not known. Known types are: %s', $field->getType(), implode('", "', Field::getValidTypes()) ) ); } // handle array values if (is_array($value)) { $value = '|' . implode('|', $value) . '|'; } $luceneFieldType = $this->getFieldType($field); $luceneField = Lucene\Document\Field::$luceneFieldType( $field->getName(), $value, $this->encoding ); if ($field->isAggregate()) { $aggregateValues[] = $value; } $luceneDocument->addField($luceneField); } // add meta fields - used internally for showing the search results, etc. $luceneDocument->addField(Lucene\Document\Field::keyword(self::ID_FIELDNAME, $document->getId())); $luceneDocument->addField(Lucene\Document\Field::keyword(self::INDEX_FIELDNAME, $document->getIndex())); $luceneDocument->addField( Lucene\Document\Field::unStored(self::AGGREGATED_INDEXED_CONTENT, implode(' ', $aggregateValues)) ); $luceneDocument->addField(Lucene\Document\Field::unIndexed(self::URL_FIELDNAME, $document->getUrl())); $luceneDocument->addField(Lucene\Document\Field::unIndexed(self::TITLE_FIELDNAME, $document->getTitle())); $luceneDocument->addField( Lucene\Document\Field::unIndexed(self::DESCRIPTION_FIELDNAME, $document->getDescription()) ); $luceneDocument->addField(Lucene\Document\Field::unIndexed(self::LOCALE_FIELDNAME, $document->getLocale())); $luceneDocument->addField(Lucene\Document\Field::unIndexed(self::CLASS_TAG, $document->getClass())); $luceneDocument->addField(Lucene\Document\Field::unIndexed(self::IMAGE_URL, $document->getImageUrl())); $index->addDocument($luceneDocument); return $luceneDocument; }
{@inheritdoc}
entailment
public function deindex(Document $document, $indexName) { $index = $this->getLuceneIndex($indexName); $this->removeExisting($index, $document); $index->commit(); }
{@inheritdoc}
entailment
public function search(SearchQuery $searchQuery) { $indexNames = $searchQuery->getIndexes(); $queryString = $searchQuery->getQueryString(); $searcher = new Lucene\MultiSearcher(); foreach ($indexNames as $indexName) { $indexPath = $this->getIndexPath($indexName); if (!file_exists($indexPath)) { continue; } $searcher->addIndex($this->getIndex($indexPath, false)); } $query = Lucene\Search\QueryParser::parse($queryString); try { $luceneHits = $searcher->find($query); } catch (\RuntimeException $e) { if (!preg_match('&non-wildcard characters&', $e->getMessage())) { throw $e; } $luceneHits = []; } $endPos = count($luceneHits); $startPos = $searchQuery->getOffset(); if (null !== $searchQuery->getLimit()) { $endPos = min(count($luceneHits), $startPos + $searchQuery->getLimit()); } $hits = []; for ($pos = $startPos; $pos < $endPos; ++$pos) { /* @var Lucene\Search\QueryHit $luceneHit */ $luceneHit = $luceneHits[$pos]; $luceneDocument = $luceneHit->getDocument(); $hit = $this->factory->createQueryHit(); $document = $this->factory->createDocument(); $hit->setDocument($document); $hit->setScore($luceneHit->score); // map meta fields to document "product" $document->setId($luceneDocument->getFieldValue(self::ID_FIELDNAME)); $document->setIndex($luceneDocument->getFieldValue(self::INDEX_FIELDNAME)); $document->setTitle($luceneDocument->getFieldValue(self::TITLE_FIELDNAME)); $document->setDescription($luceneDocument->getFieldValue(self::DESCRIPTION_FIELDNAME)); $document->setLocale($luceneDocument->getFieldValue(self::LOCALE_FIELDNAME)); $document->setUrl($luceneDocument->getFieldValue(self::URL_FIELDNAME)); $document->setClass($luceneDocument->getFieldValue(self::CLASS_TAG)); $document->setImageUrl($luceneDocument->getFieldValue(self::IMAGE_URL)); $hit->setId($document->getId()); foreach ($luceneDocument->getFieldNames() as $fieldName) { $document->addField( $this->factory->createField($fieldName, $luceneDocument->getFieldValue($fieldName)) ); } $hits[] = $hit; } // The MultiSearcher does not support sorting, so we do it here. usort( $hits, function (QueryHit $documentA, QueryHit $documentB) { if ($documentA->getScore() < $documentB->getScore()) { return true; } return false; } ); return new SearchResult($hits, count($luceneHits)); }
{@inheritdoc}
entailment
public function purge($indexName) { $indexPath = $this->getIndexPath($indexName); $fs = new Filesystem(); $fs->remove($indexPath); }
{@inheritdoc}
entailment
public function listIndexes() { if (!file_exists($this->basePath)) { return []; } $finder = new Finder(); $indexDirs = $finder->directories()->depth('== 0')->in($this->basePath); $names = []; foreach ($indexDirs as $file) { /* @var $file \Symfony\Component\Finder\SplFileInfo; */ $names[] = $file->getBasename(); } return $names; }
{@inheritdoc}
entailment
private function getLuceneIndex($indexName) { $indexPath = $this->getIndexPath($indexName); if (!file_exists($indexPath)) { $this->getIndex($indexPath, true); } return $this->getIndex($indexPath, false); }
Return (or create) a Lucene index for the given name. @param string $indexName @return Index
entailment
private function removeExisting(Index $index, Document $document) { $hits = $index->find(self::ID_FIELDNAME . ':' . $document->getId()); foreach ($hits as $hit) { $index->delete($hit->id); } }
Remove the existing entry for the given Document from the index, if it exists. @param Index $index The Zend Lucene Index @param Document $document The Massive Search Document
entailment
private function getIndex($indexPath, $create = false) { $index = new Index($indexPath, $create); $index->setHideException($this->hideIndexException); return $index; }
Return the index. Note that we override the default ZendSeach index to allow us to catch the exception thrown during __destruct when running functional tests. @param string $indexPath @param bool $create Create an index or open it @return Index
entailment
private function getFieldType(Field $field) { if ($field->isStored() && $field->isIndexed()) { return 'text'; } if (false === $field->isStored() && $field->isIndexed()) { return 'unStored'; } if ($field->isStored() && false === $field->isIndexed()) { return 'unIndexed'; } throw new \InvalidArgumentException( sprintf( 'Field "%s" cannot be both not indexed and not stored', $field->getName() ) ); }
Return the zend lucene field type to use for the given field. @param Field $field @return string
entailment
public function initialize() { if (!$this->filesystem->exists($this->basePath)) { $this->filesystem->mkdir($this->basePath); } }
{@inheritdoc}
entailment
public function preRemove(LifecycleEventArgs $event) { $event = new DeindexEvent($event->getEntity()); $this->eventDispatcher->dispatch(SearchEvents::DEINDEX, $event); }
Deindex entities after they have been removed. @param LifecycleEventArgs $event
entailment
public function getValue($object, FieldInterface $field) { try { switch (get_class($field)) { case 'Massive\Bundle\SearchBundle\Search\Metadata\Field\Property': return $this->getPropertyValue($object, $field); case 'Massive\Bundle\SearchBundle\Search\Metadata\Field\Expression': return $this->getExpressionValue($object, $field); case 'Massive\Bundle\SearchBundle\Search\Metadata\Field\Field': return $this->getFieldValue($object, $field); case 'Massive\Bundle\SearchBundle\Search\Metadata\Field\Value': return $field->getValue(); } } catch (\Exception $e) { throw new \Exception(sprintf( 'Error encountered when trying to determine value from object "%s"', get_class($object) ), null, $e); } throw new \RuntimeException(sprintf( 'Unknown field type "%s" when trying to convert "%s" into a search document', get_class($field), get_class($object) )); }
Evaluate the value from the given object and field. @param mixed $object @param FieldInterface $field
entailment
private function getPropertyValue($object, Property $field) { return $this->accessor->getValue($object, $field->getProperty()); }
Evaluate a property (using PropertyAccess). @param mixed $object @param Property $field
entailment
private function getFieldValue($object, Field $field) { if (is_array($object)) { $path = '[' . $field->getName() . ']'; } else { $path = $field->getName(); } return $this->accessor->getValue($object, $path); }
Return a value determined from the name of the field rather than an explicit property. If the object is an array, then force the array syntax. @param mixed $object @param Field $field
entailment
private function getExpressionValue($object, Expression $field) { try { return $this->expressionLanguage->evaluate($field->getExpression(), [ 'object' => $object, ]); } catch (\Exception $e) { throw new \RuntimeException(sprintf( 'Error encountered when evaluating expression "%s"', $field->getExpression() ), null, $e); } }
Evaluate an expression (ExpressionLanguage). @param mixed $object @param Expression $field
entailment
public function purgeIndexes(IndexRebuildEvent $event) { if (!$event->getPurge()) { return; } foreach ($this->searchManager->getIndexNames() as $indexName) { $event->getOutput()->writeln('<info>Purging index</info>: ' . $indexName); $this->searchManager->purge($indexName); } }
Purges all indexes, if the purge option is set. @param IndexRebuildEvent $event
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('massive_search') ->children() ->arrayNode('services') ->addDefaultsifNotSet() ->children() ->scalarNode('factory')->defaultValue('massive_search.factory_default')->end() ->end() ->end() ->enumNode('adapter') ->values(['zend_lucene', 'elastic', 'test']) ->defaultValue('zend_lucene')->end() ->arrayNode('adapters') ->addDefaultsifNotSet() ->children() ->arrayNode('zend_lucene') ->addDefaultsifNotSet() ->children() ->booleanNode('hide_index_exception')->defaultValue(false)->end() ->scalarNode('basepath')->defaultValue('%kernel.root_dir%/data')->end() ->scalarNode('encoding')->defaultValue('UTF-8')->end() ->end() ->end() ->arrayNode('elastic') ->addDefaultsifNotSet() ->children() ->scalarNode('version')->defaultValue('2.2')->end() ->arrayNode('hosts') ->defaultValue(['localhost:9200']) ->prototype('scalar')->end() ->end() ->end() ->end() ->end() ->end() ->arrayNode('metadata') ->addDefaultsIfNotSet() ->children() ->scalarNode('prefix')->defaultValue('massive')->end() ->scalarNode('cache_dir')->defaultValue('%kernel.cache_dir%/massive-search')->end() ->booleanNode('debug')->defaultValue('%kernel.debug%')->end() ->end() ->end() ->arrayNode('persistence') ->addDefaultsifNotSet() ->children() ->arrayNode('doctrine_orm') ->canBeEnabled() ->end() ->end() ->end() ->end(); return $treeBuilder; }
Returns the config tree builder. @return TreeBuilder
entailment
public function createField($name, $value, $type = Field::TYPE_STRING, $stored = true, $indexed = true, $aggregated = false) { return new Field($name, $value, $type, $stored, $indexed, $aggregated); }
Make a new search field (fields are contained within documents). @return Field
entailment
public function onDeindex(DeindexEvent $event) { try { $this->searchManager->deindex($event->getSubject()); } catch (MetadataNotFoundException $ex) { // no metadata found => do nothing } }
Deindex subject from event. @param DeindexEvent $event
entailment
public function decorate(IndexMetadataInterface $indexMetadata, $object, Document $document) { $indexName = $this->decorator->decorate($indexMetadata, $object, $document); $locale = $document->getLocale(); if (!$locale) { return $indexName; } return $indexName . '-' . $locale . '-i18n'; }
{@inheritdoc}
entailment
public function isVariant($indexName, $decoratedIndexName, array $options = []) { if (!$this->decorator->isVariant($indexName, $this->removeLocale($decoratedIndexName), $options)) { return false; } if ($indexName == $decoratedIndexName) { return true; } $locale = '[a-zA-Z_]+'; if (isset($options['locale'])) { $locale = $options['locale']; } return (bool) preg_match(sprintf( '/^%s-%s-i18n$/', $indexName, $locale ), $decoratedIndexName); }
{@inheritdoc}
entailment
public function setCheckpoint($providerName, $classFqn, $value) { if (!is_scalar($value)) { throw new \InvalidArgumentException(sprintf( 'Only scalar values may be passed as a checkpoint value, got "%s"', gettype($value) )); } $data = $this->getCheckpoints(); if (!isset($data[$providerName])) { $data[$providerName] = []; } $data[$providerName][$classFqn] = $value; $this->saveCheckpoints($data); }
{@inheritdoc}
entailment
public function getCheckpoint($providerName, $classFqn) { $data = $this->getCheckpoints(); if (isset($data[$providerName][$classFqn])) { return $data[$providerName][$classFqn]; } return; }
{@inheritdoc}
entailment
public function removeCheckpoints($providerName) { $data = $this->getCheckpoints(); if (isset($data[$providerName])) { unset($data[$providerName]); $this->saveCheckpoints($data); } }
{@inheritdoc}
entailment
public function rtmpPublishUrl() { switch ($this->publishSecurity) { case 'static': $url = $this->_rtmpPublishStaticUrl(); break; case 'dynamic': $url = $this->_rtmpPublishDynamicUrl(); break; default: $url = $this->_rtmpPublishBaseUrl(); break; } return $url; }
-------------------------------------------------------------------------------
entailment
public function rtmpLiveUrls() { $urls = array(); $url = sprintf("rtmp://%s/%s/%s", $this->hosts["live"]["rtmp"], $this->hub, $this->title); $urls['ORIGIN'] = $url; if (isset($this->profiles) && !empty($this->profiles)) { foreach ($this->profiles as $profile) { $urls[$profile] = sprintf("%s@%s", $url, $profile); } } return $urls; }
--------------------------------------------------------------------------------
entailment
public function hlsLiveUrls() { $urls = array(); $urls['ORIGIN'] = sprintf("http://%s/%s/%s.m3u8", $this->hosts["live"]["hls"], $this->hub, $this->title); if (isset($this->profiles) && !empty($this->profiles)) { foreach ($this->profiles as $profile) { $urls[$profile] = sprintf("http://%s/%s/%s@%s.m3u8", $this->hosts["live"]["hls"], $this->hub, $this->title, $profile); } } return $urls; }
--------------------------------------------------------------------------------
entailment
public function hlsPlaybackUrls($start = -1, $end = -1) { $name = sprintf("%d", time()); $resp = $this->saveAs($name, NULL, $start, $end); $urls = array(); $urls['ORIGIN'] = $resp["url"]; return $urls; }
--------------------------------------------------------------------------------
entailment
public function findDocumentById($id) { $response = $this->request('GET', '/' . $id); if ($response->getStatusCode() !== 200) { return null; } return $this->documentFactory->createFromResponse($this, $id, $response); }
Returns a document @param string $id @return Document
entailment
public function createCommand($indexName, $clientName = null) { if (!in_array($indexName, $this->indexInformer->getAllIndexNames())) { $this->outputFormatted("The index <b>%s</b> is not configured in the current application", [$indexName]); $this->quit(1); } $client = $this->clientFactory->create($clientName); try { $index = new Index($indexName, $client); if ($index->exists()) { $this->outputFormatted("The index <b>%s</b> exists", [$indexName]); $this->quit(1); } $index->create(); $this->outputFormatted("Index <b>%s</b> created with success", [$indexName]); } catch (Exception $exception) { $this->outputFormatted("Unable to create an index named: <b>%s</b>", [$indexName]); $this->quit(1); } }
Create a new index in ElasticSearch @param string $indexName The name of the new index @param string $clientName The client name to use @return void
entailment
public function showConfiguredTypesCommand() { $classesAndAnnotations = $this->indexInformer->getClassesAndAnnotations(); $this->outputFormatted("<b>Available document type</b>"); /** @var $annotation Indexable */ foreach ($classesAndAnnotations as $className => $annotation) { $this->outputFormatted("%s", [$className], 4); } }
List available document type @return void
entailment
public function statusCommand($object = null, $conductUpdate = false, $clientName = null) { $result = new ErrorResult(); $client = $this->clientFactory->create($clientName); $classesAndAnnotations = $this->indexInformer->getClassesAndAnnotations(); if ($object !== null) { if (!isset($classesAndAnnotations[$object])) { $this->outputFormatted("Error: Object '<b>%s</b>' is not configured correctly, check the Indexable annotation.", [$object]); $this->quit(1); } $classesAndAnnotations = [$object => $classesAndAnnotations[$object]]; } array_walk($classesAndAnnotations, function (Indexable $annotation, $className) use ($result, $client, $conductUpdate) { $this->outputFormatted("Object \x1b[33m%s\x1b[0m", [$className], 4); $this->outputFormatted("Index <b>%s</b> Type <b>%s</b>", [ $annotation->indexName, $annotation->typeName, ], 8); $count = $client->findIndex($annotation->indexName)->findType($annotation->typeName)->count(); if ($count === null) { $result->forProperty($className)->addError(new Error('ElasticSearch was unable to retrieve a count for the type "%s" at index "%s". Probably these don\' exist.', 1340289921, [ $annotation->typeName, $annotation->indexName, ])); } $this->outputFormatted("Documents in Search: <b>%s</b>", [$count !== null ? $count : "\x1b[41mError\x1b[0m"], 8); try { $count = $this->persistenceManager->createQueryForType($className)->count(); } catch (\Exception $exception) { $count = null; $result->forProperty($className)->addError(new Error('The persistence backend was unable to retrieve a count for the type "%s". The exception message was "%s".', 1340290088, [ $className, $exception->getMessage(), ])); } $this->outputFormatted("Documents in Persistence: <b>%s</b>", [$count !== null ? $count : "\x1b[41mError\x1b[0m"], 8); if (!$result->forProperty($className)->hasErrors()) { $states = $this->getModificationsNeededStatesAndIdentifiers($client, $className); if ($conductUpdate) { $inserted = 0; $updated = 0; foreach ($states[ObjectIndexer::ACTION_TYPE_CREATE] as $identifier) { try { $this->objectIndexer->indexObject($this->persistenceManager->getObjectByIdentifier($identifier, $className)); $inserted++; } catch (\Exception $exception) { $result->forProperty($className)->addError(new Error('An error occurred while trying to add an object to the ElasticSearch backend. The exception message was "%s".', 1340356330, [$exception->getMessage()])); } } foreach ($states[ObjectIndexer::ACTION_TYPE_UPDATE] as $identifier) { try { $this->objectIndexer->indexObject($this->persistenceManager->getObjectByIdentifier($identifier, $className)); $updated++; } catch (\Exception $exception) { $result->forProperty($className)->addError(new Error('An error occurred while trying to update an object to the ElasticSearch backend. The exception message was "%s".', 1340358590, [$exception->getMessage()])); } } $this->outputFormatted("Objects inserted: <b>%s</b>", [$inserted], 8); $this->outputFormatted("Objects updated: <b>%s</b>", [$updated], 8); } else { $this->outputFormatted("Modifications needed: <b>create</b> %d, <b>update</b> %d", [ count($states[ObjectIndexer::ACTION_TYPE_CREATE]), count($states[ObjectIndexer::ACTION_TYPE_UPDATE]), ], 8); } } }); if ($result->hasErrors()) { $this->outputLine(); $this->outputLine('The following errors occurred:'); /** @var $error Error */ foreach ($result->getFlattenedErrors() as $className => $errors) { foreach ($errors as $error) { $this->outputLine(); $this->outputFormatted("<b>\x1b[41mError\x1b[0m</b> for \x1b[33m%s\x1b[0m:", [$className], 8); $this->outputFormatted((string)$error, [], 4); } } } }
Shows the status of the current mapping @param string $object Class name of a domain object. If given, will only work on this single object @param boolean $conductUpdate Set to TRUE to conduct the required corrections @param string $clientName The client name to use @return void
entailment
public function indexObject($object, $signalInformation = null, Client $client = null) { $type = $this->getIndexTypeForObject($object, $client); if ($type === null) { return null; } $data = $this->getIndexablePropertiesAndValuesFromObject($object); $id = $this->persistenceManager->getIdentifierByObject($object); $document = new Document($type, $data, $id); $document->store(); }
(Re-) indexes an object to the ElasticSearch index, no matter if the change is actually required. @param object $object @param string $signalInformation Signal information, if called from a signal @param Client $client @return void
entailment
protected function getIndexTypeForObject($object, Client $client = null) { if ($client === null) { $client = $this->client; } $className = TypeHandling::getTypeForValue($object); $indexAnnotation = $this->indexInformer->getClassAnnotation($className); if ($indexAnnotation === null) { return null; } $index = $client->findIndex($indexAnnotation->indexName); return new GenericType($index, $indexAnnotation->typeName); }
Returns the ElasticSearch type for a specific object, by its annotation @param object $object @param Client $client @return GenericType
entailment
protected function getIndexablePropertiesAndValuesFromObject($object) { $className = TypeHandling::getTypeForValue($object); $data = []; foreach ($this->indexInformer->getClassProperties($className) as $propertyName) { if (ObjectAccess::isPropertyGettable($object, $propertyName) === false) { continue; } $value = ObjectAccess::getProperty($object, $propertyName); if (($transformAnnotation = $this->reflectionService->getPropertyAnnotation($className, $propertyName, TransformAnnotation::class)) !== null) { $value = $this->transformerFactory->create($transformAnnotation->type)->transformByAnnotation($value, $transformAnnotation); } $data[$propertyName] = $value; } return $data; }
Returns a multidimensional array with the indexable, probably transformed values of an object @param object $object @return array
entailment
public function objectIndexActionRequired($object, Client $client = null) { $type = $this->getIndexTypeForObject($object, $client); if ($type === null) { return null; } $id = $this->persistenceManager->getIdentifierByObject($object); $document = $type->findDocumentById($id); if ($document !== null) { $objectData = $this->getIndexablePropertiesAndValuesFromObject($object); if (strcmp(json_encode($objectData), json_encode($document->getData())) === 0) { $actionType = null; } else { $actionType = self::ACTION_TYPE_UPDATE; } } else { $actionType = self::ACTION_TYPE_CREATE; } return $actionType; }
Returns if, and what, treatment an object requires regarding the index state, i.e. it checks the given object against the index and tells whether deletion, update or creation is required. @param object $object @param Client $client @return string one of this' ACTION_TYPE_* constants or NULL if no action is required
entailment
protected function registerFunctions() { parent::registerFunctions(); $this->addFunction($this->createJoinFunction()); $this->addFunction($this->createMapFunction()); }
{@inheritdoc}
entailment
private function createJoinFunction() { return new ExpressionFunction( 'join', function ($glue, $elements) { return sprintf('join(%s, %s)', $glue, $elements); }, function (array $values, $glue, $elements) { return implode($glue, $elements); } ); }
Join is an alias for PHP implode:. join(',', ['one', 'two', 'three']) = "one,two,three" @return ExpressionFunction
entailment
private function createMapFunction() { return new ExpressionFunction( 'map', function ($elements, $expression) { throw new \Exception('Map function does not support compilation'); }, function (array $values, $elements, $expression) { if (empty($elements)) { return []; } $result = []; foreach ($elements as $element) { $result[] = $this->evaluate($expression, [ 'el' => $element, ]); } return $result; } ); }
Map is an analogue for array_map. The callback in the form of an expression. The nested expression has one variable, "el". For example: map({'foo': 'one', 'foo': 'two'}, 'el["foo"]'}) = array('one', 'two'); @return ExpressionFunction
entailment
public static function resolve(array $controllers) { $callbacks = []; foreach ($controllers as $controller) { $qualifiedController = '\\' . trim($controller, '\\'); $callbacks[$controller] = function (ContainerInterface $container) use ($qualifiedController) { $controller = new $qualifiedController(); if ($controller instanceof Controller) { $controller->setContainer($container); } return $controller; }; } return $callbacks; }
Create service callbacks. @param array $controllers @return array
entailment
public function index(Document $document, $indexName) { $fields = []; foreach ($document->getFields() as $massiveField) { $type = $massiveField->getType(); $value = $massiveField->getValue(); switch ($type) { case Field::TYPE_STRING: case Field::TYPE_ARRAY: $fields[$this->encodeFieldName($massiveField->getName())] = $value; break; case Field::TYPE_NULL: // ignore it break; default: throw new \InvalidArgumentException( sprintf( 'Search field type "%s" is not known. Known types are: %s', $massiveField->getType(), implode(', ', Field::getValidTypes()) ) ); } } $fields[self::ID_FIELDNAME] = $document->getId(); $fields[self::INDEX_FIELDNAME] = $document->getIndex(); $fields[self::URL_FIELDNAME] = $document->getUrl(); $fields[self::TITLE_FIELDNAME] = $document->getTitle(); $fields[self::DESCRIPTION_FIELDNAME] = $document->getDescription(); $fields[self::LOCALE_FIELDNAME] = $document->getLocale(); $fields[self::CLASS_TAG] = $document->getClass(); $fields[self::IMAGE_URL] = $document->getImageUrl(); // ensure that any new index name is listed when calling listIndexes $this->indexList[$indexName] = $indexName; $params = [ 'id' => $document->getId(), 'index' => $indexName, 'type' => $this->documentToType($document), 'body' => $fields, ]; $this->client->index($params); }
{@inheritdoc}
entailment
public function deindex(Document $document, $indexName) { $params = [ 'index' => $indexName, 'type' => $this->documentToType($document), 'id' => $document->getId(), 'refresh' => true, ]; try { $this->client->delete($params); } catch (Missing404Exception $e) { // ignore 404 exceptions } }
{@inheritdoc}
entailment
public function search(SearchQuery $searchQuery) { $indexNames = $searchQuery->getIndexes(); $queryString = $searchQuery->getQueryString(); $params['index'] = implode(',', $indexNames); $params['body'] = [ 'query' => [ 'query_string' => [ 'query' => $queryString, ], ], 'from' => $searchQuery->getOffset(), ]; if (!empty($searchQuery->getLimit())) { $params['body']['size'] = $searchQuery->getLimit(); } foreach ($searchQuery->getSortings() as $sort => $order) { $params['body']['sort'][] = [ $sort => [ 'order' => $order, ], ]; } $res = $this->client->search($params); $elasticHits = $res['hits']['hits']; $hits = []; foreach ($elasticHits as $elasticHit) { $hit = $this->factory->createQueryHit(); $document = $this->factory->createDocument(); $hit->setDocument($document); $hit->setScore($elasticHit['_score']); $document->setId($elasticHit['_id']); $elasticSource = $elasticHit['_source']; if (isset($elasticSource[self::INDEX_FIELDNAME])) { $document->setIndex($elasticSource[self::INDEX_FIELDNAME]); } if (isset($elasticSource[self::TITLE_FIELDNAME])) { $document->setTitle($elasticSource[self::TITLE_FIELDNAME]); } if (isset($elasticSource[self::DESCRIPTION_FIELDNAME])) { $document->setDescription($elasticSource[self::DESCRIPTION_FIELDNAME]); } if (isset($elasticSource[self::LOCALE_FIELDNAME])) { $document->setLocale($elasticSource[self::LOCALE_FIELDNAME]); } if (isset($elasticSource[self::URL_FIELDNAME])) { $document->setUrl($elasticSource[self::URL_FIELDNAME]); } if (isset($elasticSource[self::CLASS_TAG])) { $document->setClass($elasticSource[self::CLASS_TAG]); } if (isset($elasticSource[self::IMAGE_URL])) { $document->setImageUrl($elasticSource[self::IMAGE_URL]); } $hit->setId($document->getId()); foreach ($elasticSource as $fieldName => $fieldValue) { $document->addField($this->factory->createField($this->decodeFieldName($fieldName), $fieldValue)); } $hits[] = $hit; } return new SearchResult($hits, $res['hits']['total']); }
{@inheritdoc}
entailment
public function getStatus() { $indices = $this->getIndexStatus(); $indexes = $indices['indices']; $status = []; foreach ($indexes as $indexName => $index) { foreach ($index as $field => $value) { $status['idx:' . $indexName . '.' . $field] = substr(trim(json_encode($value)), 0, 100); } } return $status; }
{@inheritdoc}
entailment
public function purge($indexName) { try { $this->client->indices()->delete(['index' => $indexName]); $this->indexListLoaded = false; } catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e) { } }
{@inheritdoc}
entailment
public function listIndexes() { if (!$this->indexListLoaded) { $indices = $this->getIndexStatus(); $indexes = $indices['indices']; $this->indexList = array_combine( array_keys($indexes), array_keys($indexes) ); $this->indexListLoaded = true; } return $this->indexList; }
{@inheritdoc}
entailment
private function getIndexStatus() { if (version_compare($this->version, '2.2', '>')) { return $this->client->indices()->stats(['index' => '_all']); } return $this->client->indices()->status(['index' => '_all']); }
Returns index-status. @return array
entailment
public function jsonSerialize() { return [ 'id' => $this->id, 'title' => $this->title, 'description' => $this->description, 'class' => $this->class, 'url' => $this->url, 'image_url' => $this->imageUrl, 'locale' => $this->locale, ]; }
{@inheritdoc}
entailment
public function loadMetadataFromFile(\ReflectionClass $class, $file) { $classMetadata = $this->factory->createClassMetadata($class->name); $xml = simplexml_load_file($file); if (count($xml->children()) > 1) { throw new \InvalidArgumentException(sprintf( 'Only one mapping allowed per class in file "%s', $file )); } if (0 == count($xml->children())) { throw new \InvalidArgumentException(sprintf('No mapping in file "%s"', $file)); } $mapping = $xml->children()->mapping; $mappedClassName = (string) $mapping['class']; if ($class->getName() !== $mappedClassName) { throw new \InvalidArgumentException(sprintf( 'Mapping in file "%s" does not correspond to class "%s", is a mapping for "%s"', $file, $class->getName(), $mappedClassName )); } $indexMapping = $this->getIndexMapping($mapping); $this->validateMapping($indexMapping, $file); // note that fields cannot be overridden in contexts $fields = $mapping->fields->children(); $indexMapping['fields'] = []; foreach ($fields as $field) { $fieldName = (string) $field['name']; $fieldType = $field['type']; $indexMapping['fields'][$fieldName] = [ 'type' => (string) $fieldType, 'field' => $this->getField($field, $fieldName), ]; } if ($mapping->reindex) { if ($mapping->reindex['repository-method']) { $classMetadata->setReindexRepositoryMethod((string) $mapping->reindex['repository-method']); } } $indexMappings = array_merge( [ '_default' => $indexMapping, ], $this->extractContextMappings($mapping, $indexMapping) ); foreach ($indexMappings as $contextName => $mapping) { $indexMetadata = $this->factory->createIndexMetadata(); $indexMetadata->setIndexName($mapping['index']); $indexMetadata->setIdField($mapping['id']); $indexMetadata->setLocaleField($mapping['locale']); $indexMetadata->setTitleField($mapping['title']); $indexMetadata->setUrlField($mapping['url']); $indexMetadata->setDescriptionField($mapping['description']); $indexMetadata->setImageUrlField($mapping['image']); foreach ($mapping['fields'] as $fieldName => $fieldData) { $indexMetadata->addFieldMapping($fieldName, $fieldData); } $classMetadata->addIndexMetadata($contextName, $indexMetadata); } return $classMetadata; }
{@inheritdoc}
entailment
private function getMapping(\SimpleXmlElement $mapping, $field) { $field = $mapping->$field; if (!$field->getName()) { return; } return $this->getField($field); }
Return the value object for the mapping. @param \SimpleXmlElement $mapping @param mixed $field
entailment
private function extractContextMappings(\SimpleXmlElement $mapping, $indexMapping) { $contextMappings = []; foreach ($mapping->context as $context) { if (!isset($context['name'])) { throw new \InvalidArgumentException(sprintf( 'No name given to context in XML mapping file for "%s"', $mapping['class'] )); } $contextName = (string) $context['name']; $contextMapping = $this->getIndexMapping($context); $contextMapping = array_filter($contextMapping, function ($value) { if (null === $value) { return false; } return true; }); $contextMappings[$contextName] = array_merge( $indexMapping, $contextMapping ); } return $contextMappings; }
Overwrite the default mapping if there exists a <context> section which matches the context given in the constructor of this class. @param \SimpleXmlElement $mapping
entailment
public function convert($value, $from) { if (!$this->hasConverter($from)) { throw new ConverterNotFoundException($from); } return $this->converter[$from]->convert($value); }
{@inheritdoc}
entailment
public function execute(InputInterface $input, OutputInterface $output) { $formatterHelper = new FormatterHelper(); $startTime = microtime(true); if ('prod' !== $this->env) { $output->writeln( $formatterHelper->formatBlock( sprintf( 'WARNING: You are running this command in the `%s` environment - this may increase memory usage. Running in `prod` environment is generally better.', $this->env ), 'comment', true ) ); } $batchSize = $input->getOption('batch-size'); $providerNames = $this->resumeManager->getUnfinishedProviders(); if (count($providerNames) > 0) { foreach ($providerNames as $providerName) { $question = new ConfirmationQuestion(sprintf( '<question>Provider "%s" did not finish. Do you wish to resume?</question> ', $providerName )); $response = $this->questionHelper->ask($input, $output, $question, true); if (false === $response) { $this->resumeManager->removeCheckpoints($providerName); } } } $providerNames = $input->getOption('provider'); if (empty($providerNames)) { $providers = $this->providerRegistry->getProviders(); } else { $providers = []; foreach ($providerNames as $providerName) { $providers[$providerName] = $this->providerRegistry->getProvider($providerName); } } foreach ($providers as $providerName => $provider) { $output->writeln(sprintf('<info>provider "</info>%s<info>"</info>', $providerName)); $output->write(PHP_EOL); foreach ($provider->getClassFqns() as $classFqn) { $return = $this->reindexClass($output, $provider, $providerName, $classFqn, $batchSize); if (false === $return) { break; } } $this->resumeManager->removeCheckpoints($providerName); } $output->writeln(sprintf( '<info>Index rebuild completed (</info>%ss %sb</info><info>)</info>', number_format(microtime(true) - $startTime, 2), number_format(memory_get_usage()) )); }
{@inheritdoc}
entailment
public function addSorting($sort, $order = SearchQuery::SORT_ASC) { $this->searchQuery->addSorting($sort, $order); return $this; }
Set the sort Field. @param string $sort @param string $order @return SearchQueryBuilder
entailment
public function fix(SplFileInfo $file, Tokens $tokens): void { foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) { /** @var \PhpCsFixer\Tokenizer\Token $token */ $doc = new DocBlock($token->getContent()); foreach ($doc->getAnnotations() as $annotation) { if ($this->isRelationAnnotation($annotation)) { $this->fixRelationAnnotation($doc, $annotation); $token->setContent($doc->getContent()); } } } }
{@inheritdoc}
entailment
public function register() { $this->mergeConfigFrom(__DIR__ . '/../../config/laravelpdf.php', 'laravelpdf'); $this->app->singleton('pdf', function ($app) { return new PDF(config('laravelpdf.executable'), storage_path()); }); }
Register the service provider. @return void
entailment
protected function _create($class, $alias, $config) { $instance = new $class($this->_collection, $config); $enable = isset($config['enabled']) ? $config['enabled'] : true; if ($enable) { $this->eventManager()->on($instance); } $methods = $this->_getMethods($instance, $class, $alias); $this->_methodMap += $methods['methods']; $this->_finderMap += $methods['finders']; return $instance; }
Overridden _create() method that injects a BaseCollection object into a MongoBehavior rather than a Behavior object. @param string $class @param string $alias @param array $config @return mixed
entailment
public function getMimeType() { // return mime type ala mimetype extension $finfo = finfo_open(FILEINFO_MIME); $mime = finfo_file($finfo, $this->getFullPath()); return $mime; }
Get the mime type for the file. @param FileInterface $file @return string
entailment
public function select(callable $filter) { if (! $this->collection) { return new ReviewCollection(); } $filtered = array_filter($this->collection, $filter); return new ReviewCollection($filtered); }
Filters the collection with the given closure, returning a new collection. @return ReviewCollection
entailment
public function forFile(FileInterface $file) { $filter = function ($review) use ($file) { if ($review->canReview($file)) { return true; } return false; }; return $this->select($filter); }
Returns a filtered ReviewCollection that should be run against the given file. @param FileInterface $file @return ReviewCollection
entailment
public function forMessage(CommitMessageInterface $message) { $filter = function ($review) use ($message) { if ($review->canReview($message)) { return true; } return false; }; return $this->select($filter); }
Returns a filtered ReviewCollection that should be run against the given message. @param CommitMessage $message @return ReviewCollection
entailment
public function configure(array $configuration = null): void { if ($configuration !== null) { $this->analyzedNamespaces = $this->extractNamespaces($configuration); } }
{@inheritdoc}
entailment
public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([T_PRIVATE]) && $this->checkNamespace($tokens); }
{@inheritdoc}
entailment
public function fix(SplFileInfo $file, Tokens $tokens): void { foreach ($tokens->findGivenKind(T_PRIVATE) as $index => $privateToken) { $tokens[$index] = new Token([T_PROTECTED, 'protected']); } }
{@inheritdoc}
entailment
public function getLevelName() { switch ($this->getLevel()) { case self::LEVEL_INFO: return 'Info'; case self::LEVEL_WARNING: return 'Warning'; case self::LEVEL_ERROR: return 'Error'; default: throw new \UnexpectedValueException('Level was set to ' . $this->getLevel()); } }
Gets the Issues level as a string.
entailment
public function getColour() { switch ($this->level) { case self::LEVEL_INFO: return 'cyan'; case self::LEVEL_WARNING: return 'brown'; case self::LEVEL_ERROR: return 'red'; default: throw new \UnexpectedValueException('Could not get a colour. Level was set to ' . $this->getLevel()); } }
Gets the colour to use when echoing to the console. @return string
entailment
public function select(callable $filter) { if (! $this->collection) { return new IssueCollection(); } $filtered = array_filter($this->collection, $filter); return new IssueCollection($filtered); }
Filters the collection with the given closure, returning a new collection. @return IssueCollection
entailment
public function forLevel($option) { // Only return issues matching the level. $filter = function ($issue) use ($option) { if ($issue->matches($option)) { return true; } return false; }; return $this->select($filter); }
Returns a new IssueCollection filtered by the given level option. @param int $level @return IssueCollection
entailment
public function getStagedFiles() { $base = $this->getProjectBase(); $files = new FileCollection(); foreach ($this->getFiles() as $file) { $fileData = explode("\t", $file); $status = reset($fileData); $relativePath = end($fileData); $fullPath = rtrim($base . DIRECTORY_SEPARATOR . $relativePath); $file = new File($status, $fullPath, $base); $this->saveFileToCache($file); $files->append($file); } return $files; }
Gets a list of the files currently staged under git. Returns either an empty array or a tab separated list of staged files and their git status. @link http://git-scm.com/docs/git-status @return FileCollection
entailment
public function getCommitMessage($file = null) { if ($file) { $hash = null; $message = file_get_contents($file); } else { list($hash, $message) = explode(PHP_EOL, $this->getLastCommitMessage(), 2); } return new CommitMessage($message, $hash); }
Get a commit message by file or log. If no file name is provided, the last commit message will be used. @param string $file @return CommitMessage
entailment
private function getFiles() { $process = new Process('git diff --cached --name-status --diff-filter=ACMR'); $process->run(); if ($process->isSuccessful()) { return array_filter(explode("\n", $process->getOutput())); } return []; }
Gets the list of files from the index. @return array
entailment
private function saveFileToCache(FileInterface $file) { $cachedPath = sys_get_temp_dir() . self::CACHE_DIR . $file->getRelativePath(); if (! is_dir(dirname($cachedPath))) { mkdir(dirname($cachedPath), 0700, true); } $cmd = sprintf('git show :%s > %s', $file->getRelativePath(), $cachedPath); $process = new Process($cmd); $process->run(); $file->setCachedPath($cachedPath); return $file; }
Saves a copy of the cached version of the given file to a temp directory. @param FileInterface $file @return FileInterface
entailment
public function loadViews($viewNames = array(), $data = array(), $mergeData = array()) { $this->children = array(); foreach ($viewNames as $key => $viewName) { $className = get_class(); $item = new $className($this->cmd, $this->folder); $item->loadView($viewName, $data, $mergeData); $this->children[] = $item; } return $this; }
Mass version of the loadView function. @param array $viewNames Array of Laravel view names to include in resulting page. Order matters. @param array $data Data array is shared across all views. @param array $mergeData @return $this @see: loadView()
entailment
public function loadHTMLs($htmls) { $this->children = array(); foreach ($htmls as $key => $html) { $className = get_class(); $item = new $className($this->cmd, $this->folder); /* @var \Inline\LaravelPDF\PDF $item */ $item->loadHTML($html); $this->children[] = $item; } return $this; }
Mass loads HTML Content. @param array string $htmls @return $this
entailment
protected function getInputSource() { if (empty($this->children)) { return parent::getInputSource(); } $childPaths = []; foreach ($this->children as $child) { $childPaths[] = $child->getInputSource(); } return implode(" ", $childPaths); }
Updated version which can handle multiple source files. @return string
entailment
public function review(ReporterInterface $reporter, ReviewableInterface $file) { $cmd = sprintf('file %s | grep --fixed-strings --quiet "CRLF"', $file->getFullPath()); $process = $this->getProcess($cmd); $process->run(); if ($process->isSuccessful()) { $message = 'File contains CRLF line endings'; $reporter->error($message, $this, $file); } }
Checks if the set file contains any CRLF line endings. @link http://stackoverflow.com/a/3570574
entailment
public function getContext() { $context = [ 'log_cmd_insert' => [$this, 'onInsert'], 'log_cmd_delete' => [$this, 'onDelete'], 'log_cmd_update' => [$this, 'onUpdate'], 'log_insert' => [$this, 'onInsert'], 'log_delete' => [$this, 'onDelete'], 'log_update' => [$this, 'onUpdate'], 'log_batchinsert' => [$this, 'onBatchInsert'], 'log_write_batch' => [$this, 'onBatchInsert'], 'log_query' => [$this, 'onQuery'] ]; return $context; }
Returns the context array for being converted into a stream context by the MongoConnection class. @return array
entailment
public function addReviews(ReviewCollection $reviews) { foreach ($reviews as $review) { $this->reviews->append($review); } return $this; }
Appends a ReviewCollection to the current list of reviews. @param ReviewCollection $checks @return StaticReview
entailment
public function files(FileCollection $files) { foreach ($files as $key => $file) { $this->getReporter()->progress($key + 1, count($files)); foreach ($this->getReviews()->forFile($file) as $review) { $review->review($this->getReporter(), $file); } } return $this; }
Runs through each review on each file, collecting any errors. @return StaticReview
entailment
public function message(CommitMessageInterface $message) { foreach ($this->getReviews()->forMessage($message) as $review) { $review->review($this->getReporter(), $message); } return $this; }
Runs through each review on the commit, collecting any errors. @return StaticReview
entailment
public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound(self::ACCESS_TOKENS); }
{@inheritdoc}
entailment
public function fix(\SplFileInfo $file, Tokens $tokens): void { $allDocBlocks = $this->findAllDocBlocks($tokens); foreach ($allDocBlocks as $position => $docBlock) { if (!$this->areThereAnyAccessAnnotation($docBlock)) { continue; } if ($this->followingTokenIsAccessModifier($tokens, $position)) { $this->removeAllAccessAnnotations($docBlock); $this->rewriteDocBlock($tokens, $docBlock, $position); } if ($this->areThereAnyEmptyAccessAnnotation($docBlock)) { $this->removeEmptyAccessAnnotations($docBlock); $this->rewriteDocBlock($tokens, $docBlock, $position); } } }
{@inheritdoc}
entailment
public function getMongoCollectionName() { // Get full namespaced class name $class = get_class($this); $split_array = explode('\\', $class); // Split into namespaces and get the last namespace as the class name $final = $split_array[count($split_array) - 1]; // Cut the final 10 characters off of the class (Collection from UsersCollection) and return just the collection return Inflector::tableize(substr($final, 0, -10)); }
Infers the name of the Mongo collection inside of the database based on the namespace of the current class. @return string
entailment
public function setMongaCollection($collection_name) { $this->collection = $this->database->collection($collection_name); return $this->collection; }
Sets a new collection property based on the lowercase, tableized collection name passed in as the first arg. @param string $collection_name @return mixed
entailment
public function find($query = [], $fields = [], $findOne = false) { $before_find_event = $this->dispatchEvent('Model.beforeFind', compact('query', 'fields', 'findOne')); if (!empty($before_find_event->result['query']) && $before_find_event->result['query'] !== $query) { $query = $before_find_event->result['query']; } if (!empty($before_find_event->result['fields']) && $before_find_event->result['fields'] !== $fields) { $fields = $before_find_event->result['fields']; } if ($before_find_event->isStopped()) { return false; } return $this->collection->find($query, $fields, $findOne); }
Wraps Mongoa's native `find()` function on their Collection object. If the beforeFind() method is defined, calls that method with this methods arguments and allows direct modification of the $query and $fields arguments before the find query is called. @param array $query @param array $fields @param bool $findOne @return mixed
entailment
public function save($document, $options = []) { $before_save_event = $this->dispatchEvent('Model.beforeSave', compact('document', 'options')); if (!empty($before_save_event->result['document']) && $before_save_event->result['document'] !== $document) { $document = $before_save_event->result['document']; } if ($before_save_event->isStopped()) { return false; } $results = $this->collection->save($document, $options); $after_save_event = $this->dispatchEvent('Model.afterSave', compact('results', 'document', 'options')); return $results; }
Wraps Monga's native `save()` method on their Collection object. If the beforeSave() method is defined, calls that method with this methods arguments and allows direct modification of the $document to be saved before the save is committed to the MongoDB instance. If the afterSave() method is defined, it is called after the save is successfully committed to the database. @param $document @param array $options @return mixed
entailment
public function update($values = [], $query = null, $options = []) { $before_update_event = $this->dispatchEvent('Model.beforeUpdate', compact('values', 'query')); if (!empty($before_update_event->result['values']) && $before_update_event->result['values'] !== $values) { $values = $before_update_event->result['values']; } if (!empty($before_update_event->result['query']) && $before_update_event->result['query'] !== $query) { $query = $before_update_event->result['query']; } if ($before_update_event->isStopped()) { return false; } $results = $this->collection->update($values, $query, $options); $after_update_event = $this->dispatchEvent('Model.afterUpdate', compact('results', 'query', 'values')); return $results; }
Wraps Monga's native 'update()' method on their Collection object. If the beforeUpdate() method is defined, calls that method with this methods arguments and allows direct modification of the $values and $query arguments before the update query is called. If the afterUpdate() method is defined, it is called after the update is successfully committed to the database. @param array $values @param null $query @param array $options @return mixed
entailment