sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getNormalizedIdentifier($document)
{
if (is_scalar($document)) {
throw new \InvalidArgumentException('Invalid argument, object or null required');
}
// the document is not managed
if (!$document || !$this->getDocumentManager()->contains($document)) {
return;
}
$values = $this->getIdentifierValues($document);
return $values[0];
}
|
This is just taking the id out of the array again.
{@inheritdoc}
@throws \InvalidArgumentException if $document is not an object or null
|
entailment
|
public function addIdentifiersToQuery($class, ProxyQueryInterface $queryProxy, array $idx)
{
/* @var $queryProxy ProxyQuery */
$qb = $queryProxy->getQueryBuilder();
$orX = $qb->andWhere()->orX();
foreach ($idx as $id) {
$path = $this->getBackendId($id);
$orX->same($path, $queryProxy->getAlias());
}
}
|
{@inheritdoc}
|
entailment
|
public function batchDelete($class, ProxyQueryInterface $queryProxy)
{
try {
$i = 0;
$res = $queryProxy->execute();
foreach ($res as $object) {
$this->dm->remove($object);
if (0 == (++$i % 20)) {
$this->dm->flush();
$this->dm->clear();
}
}
$this->dm->flush();
$this->dm->clear();
} catch (\Exception $e) {
throw new ModelManagerException('', 0, $e);
}
}
|
{@inheritdoc}
@throws ModelManagerException if anything goes wrong during query execution
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !\array_key_exists('value', $data) || null === $data['value']) {
return;
}
$value = trim((string) $data['value']);
$data['type'] = empty($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type'];
if (0 == \strlen($value)) {
return;
}
$where = $this->getWhere($proxyQuery);
$isComparisonLowerCase = $this->getOption('compare_case_insensitive');
$value = $isComparisonLowerCase ? strtolower($value) : $value;
switch ($data['type']) {
case ChoiceType::TYPE_EQUAL:
if ($isComparisonLowerCase) {
$where->eq()->lowerCase()->field('a.'.$field)->end()->literal($value);
} else {
$where->eq()->field('a.'.$field)->literal($value);
}
break;
case ChoiceType::TYPE_NOT_CONTAINS:
$where->fullTextSearch('a.'.$field, '* -'.$value);
break;
case ChoiceType::TYPE_CONTAINS:
if ($isComparisonLowerCase) {
$where->like()->lowerCase()->field('a.'.$field)->end()->literal('%'.$value.'%');
} else {
$where->like()->field('a.'.$field)->literal('%'.$value.'%');
}
break;
case ChoiceType::TYPE_CONTAINS_WORDS:
default:
$where->fullTextSearch('a.'.$field, $value);
}
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function buildView(FormView $view, FormInterface $form, array $options)
{
$allFieldNames = [];
foreach ($options['map'] as $value => $fieldNames) {
foreach ($fieldNames as $fieldName) {
$allFieldNames[$fieldName] = $fieldName;
}
}
$allFieldNames = array_values($allFieldNames);
$view->vars['all_fields'] = $allFieldNames;
$view->vars['map'] = $options['map'];
parent::buildView($view, $form, $options);
}
|
{@inheritdoc}
|
entailment
|
public function getDefaultOptions($type, FieldDescriptionInterface $fieldDescription)
{
$options = [];
$options['sonata_field_description'] = $fieldDescription;
switch ($type) {
case 'Sonata\DoctrinePHPCRAdminBundle\Form\Type\TreeModelType':
case 'doctrine_phpcr_odm_tree':
$options['class'] = $fieldDescription->getTargetEntity();
$options['model_manager'] = $fieldDescription->getAdmin()->getModelManager();
break;
case 'Sonata\AdminBundle\Form\Type\ModelType':
case 'sonata_type_model':
case 'Sonata\AdminBundle\Form\Type\ModelTypeList':
case 'sonata_type_model_list':
if ('child' !== $fieldDescription->getMappingType() && !$fieldDescription->getTargetEntity()) {
throw new \LogicException(sprintf(
'The field "%s" in class "%s" does not have a target model defined. Please specify the "targetDocument" attribute in the mapping for this class.',
$fieldDescription->getName(),
$fieldDescription->getAdmin()->getClass()
));
}
$options['class'] = $fieldDescription->getTargetEntity();
$options['model_manager'] = $fieldDescription->getAdmin()->getModelManager();
break;
case 'Sonata\AdminBundle\Form\Type\AdminType':
case 'sonata_type_admin':
if (!$fieldDescription->getAssociationAdmin()) {
throw $this->getAssociationAdminException($fieldDescription);
}
$options['data_class'] = $fieldDescription->getAssociationAdmin()->getClass();
$fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'admin'));
break;
case 'Sonata\CoreBundle\Form\Type\CollectionType':
case 'sonata_type_collection':
if (!$fieldDescription->getAssociationAdmin()) {
throw $this->getAssociationAdminException($fieldDescription);
}
$options['type'] = 'Sonata\AdminBundle\Form\Type\AdminType';
$options['modifiable'] = true;
$options['type_options'] = [
'sonata_field_description' => $fieldDescription,
'data_class' => $fieldDescription->getAssociationAdmin()->getClass(),
];
break;
}
return $options;
}
|
{@inheritdoc}
@throws \LogicException if a sonata_type_model field does not have a
target model configured
|
entailment
|
protected function getAssociationAdminException(FieldDescriptionInterface $fieldDescription)
{
$msg = sprintf('The current field `%s` is not linked to an admin. Please create one', $fieldDescription->getName());
if (\in_array($fieldDescription->getMappingType(), [ClassMetadata::MANY_TO_ONE, ClassMetadata::MANY_TO_MANY, 'referrers'], true)) {
if ($fieldDescription->getTargetEntity()) {
$msg .= " for the target document: `{$fieldDescription->getTargetEntity()}`";
}
$msg .= ', specify the `targetDocument` in the Reference, or the `referringDocument` in the Referrers or use the option `admin_code` to link it.';
} else {
$msg .= ' and use the option `admin_code` to link it.';
}
return new \LogicException($msg);
}
|
@param FieldDescriptionInterface $fieldDescription
@return \LogicException
|
entailment
|
public function createQuery($context = 'list')
{
$query = $this->getModelManager()->createQuery($this->getClass());
$query->setRootPath($this->getRootPath());
foreach ($this->extensions as $extension) {
$extension->configureQuery($this, $query, $context);
}
return $query;
}
|
@param string $context
@return ProxyQueryInterface
|
entailment
|
public function getSubject()
{
if (null === $this->subject && $this->request) {
$id = $this->request->get($this->getIdParameter());
if (null === $id || !preg_match('#^[0-9A-Za-z/\-_]+$#', $id)) {
$this->subject = false;
} else {
if (!UUIDHelper::isUUID($id)) {
$id = PathHelper::absolutizePath($id, '/');
}
$this->subject = $this->getObject($id);
}
}
return $this->subject;
}
|
Get subject.
Overridden to allow a broader set of valid characters in the ID, and
if the ID is not a UUID, to call absolutizePath on the ID.
@return mixed
|
entailment
|
public function toString($object)
{
if (!\is_object($object)) {
return parent::toString($object);
}
if (method_exists($object, '__toString') && null !== $object->__toString()) {
$string = (string) $object;
return '' !== $string ? $string : $this->trans('link_add', [], 'SonataAdminBundle');
}
$dm = $this->getModelManager()->getDocumentManager();
if ($dm->contains($object)) {
return PathHelper::getNodeName($dm->getUnitOfWork()->getDocumentId($object));
}
return parent::toString($object);
}
|
{@inheritdoc}
|
entailment
|
public function setAssociationMapping($associationMapping)
{
if (!\is_array($associationMapping)) {
throw new \InvalidArgumentException('The association mapping must be an array');
}
$this->associationMapping = $associationMapping;
if (isset($associationMapping['type'])) {
$this->type = $this->type ?: $associationMapping['type'];
$this->mappingType = $this->mappingType ?: $associationMapping['type'];
} else {
throw new \InvalidArgumentException('Unknown association mapping type');
}
$this->fieldName = $associationMapping['fieldName'];
}
|
{@inheritdoc}
@throws \InvalidArgumentException if the mapping is no array or of an
unknown type
|
entailment
|
public function getTargetEntity()
{
if (isset($this->associationMapping['targetDocument'])) {
return $this->associationMapping['targetDocument'];
}
if (isset($this->associationMapping['referringDocument'])) {
return $this->associationMapping['referringDocument'];
}
}
|
{@inheritdoc}
|
entailment
|
public function setFieldMapping($fieldMapping)
{
if (!\is_array($fieldMapping)) {
throw new \InvalidArgumentException('The field mapping must be an array');
}
$this->fieldMapping = $fieldMapping;
$this->type = $this->type ?: $fieldMapping['type'];
$this->mappingType = $this->mappingType ?: $fieldMapping['type'];
$this->fieldName = $this->fieldName ?: $fieldMapping['fieldName'];
}
|
{@inheritdoc}
@throws \InvalidArgumentException if the mapping information is not an array
|
entailment
|
public function execute(array $params = [], $hydrationMode = null)
{
if ($this->getSortBy()) {
switch ($this->sortOrder) {
case 'DESC':
$this->qb->orderBy()->desc()->field($this->alias.'.'.$this->sortBy);
break;
case 'ASC':
$this->qb->orderBy()->asc()->field($this->alias.'.'.$this->sortBy);
break;
default:
throw new \Exception('Unsupported sort order direction: '.$this->sortOrder);
}
}
if ($this->root) {
$this->qb->andWhere()->descendant($this->root, $this->alias);
}
return $this->qb->getQuery()->execute();
}
|
Executes the query, applying the source, the constraint of documents being of the phpcr:class of
this kind of document and builds an array of retrieved documents.
@param array $params doesn't have any effect
@param mixed $hydrationMode doesn't have any effect
@throws \Exception if $this->sortOrder is not ASC or DESC
@return array of documents
|
entailment
|
public function setSortOrder($sortOrder)
{
if (!\in_array($sortOrder, ['ASC', 'DESC'])) {
throw new \InvalidArgumentException(sprintf('The parameter $sortOrder must be one of "ASC" or "DESC", got "%s"', $sortOrder));
}
$this->sortOrder = $sortOrder;
return $this;
}
|
Set the sort ordering.
{@inheritdoc}
@param string $sortOrder (ASC|DESC)
@throws \InvalidArgumentException if $sortOrder is not one of ASC or DESC
|
entailment
|
public function configureSettings(OptionsResolver $resolver)
{
// the callables are a workaround to make bundle configuration win over the default values
// see https://github.com/sonata-project/SonataDoctrinePhpcrAdminBundle/pull/345
$resolver->setDefaults([
'template' => function (Options $options, $value) {
return $value ?: '@SonataDoctrinePHPCRAdmin/Block/tree.html.twig';
},
'id' => function (Options $options, $value) {
return $value ?: '/';
},
'selected' => function (Options $options, $value) {
return $value ?: null;
},
'routing_defaults' => function (Options $options, $value) {
return $value ?: $this->defaults;
},
]);
}
|
{@inheritdoc}
|
entailment
|
protected function getWhere(ProxyQuery $proxy)
{
$queryBuilder = $proxy->getQueryBuilder();
if (self::CONDITION_OR == $this->getCondition()) {
return $queryBuilder->orWhere();
}
return $queryBuilder->andWhere();
}
|
Add the where statement for this filter to the query.
@param ProxyQuery $proxy
|
entailment
|
public function getCacheKey($name)
{
if (isset($this->extraTemplates[$name])) {
return $name;
}
return $this->base->getCacheKey($name);
}
|
Gets the cache key to use for the cache for a given template name.
@param string $name The name of the template to load
@throws Twig_Error_Loader When $name is not found
@return string The cache key
|
entailment
|
public function isFresh($name, $time)
{
if (isset($this->extraTemplates[$name])) {
return true;
}
return $this->base->isFresh($name, $time);
}
|
Returns true if the template is still fresh.
@param string $name The template name
@param int $time Timestamp of the last modification time of the
cached template
@throws Twig_Error_Loader When $name is not found
@return bool true if the template is fresh, false otherwise
|
entailment
|
public function exists($name)
{
if (isset($this->extraTemplates[$name])) {
return true;
}
return $this->base->exists($name);
}
|
Check if we have the source code of a template, given its name.
@param string $name The name of the template to check if we can load
@return bool If the template source code is handled by this loader or not
|
entailment
|
public function share($variables, $value = null)
{
$this->jade->share($variables, $value);
return $this;
}
|
Share variables (local templates parameters) with all future templates rendered.
@example $pug->share('lang', 'fr')
@example $pug->share(['title' => 'My blog', 'today' => new DateTime()])
@param array|string $variables a variables name-value pairs or a single variable name
@param mixed $value the variable value if the first argument given is a string
@return $this
|
entailment
|
public function preRender($pugCode)
{
$parts = $this->getPugCodeLayoutStructure($pugCode);
$className = get_class($this);
foreach ($this->replacements as $name => $callable) {
$parts[0] .= ":php\n" .
" if (!function_exists('$name')) {\n" .
" function $name() {\n" .
" return call_user_func_array($className::getGlobalHelper('$name'), func_get_args());\n" .
" }\n" .
" }\n";
}
return implode('', $parts);
}
|
Pug code transformation to do before Pug render.
@param string $pugCode code input
@return string
|
entailment
|
public function getParameters(array $parameters = [])
{
foreach (['view', 'this'] as $forbiddenKey) {
if (array_key_exists($forbiddenKey, $parameters)) {
throw new \ErrorException('The "' . $forbiddenKey . '" key is forbidden.');
}
}
$sharedVariables = $this->getOptionDefault('shared_variables');
if ($sharedVariables) {
$parameters = array_merge($sharedVariables, $parameters);
}
$parameters['view'] = $this;
return $parameters;
}
|
Prepare and group input and global parameters.
@param array $parameters
@throws \ErrorException when a forbidden parameter key is used
@return array input parameters with global parameters
|
entailment
|
public function render($name, array $parameters = [])
{
$parameters = $this->getParameters($parameters);
$method = method_exists($this->jade, 'renderFile')
? [$this->jade, 'renderFile']
: [$this->jade, 'render'];
return call_user_func($method, $this->getFileFromName($name), $parameters);
}
|
Render a template by name.
@param string|\Symfony\Component\Templating\TemplateReferenceInterface $name
@param array $parameters
@throws \ErrorException when a forbidden parameter key is used
@return string
|
entailment
|
public function renderString($code, array $parameters = [])
{
$parameters = $this->getParameters($parameters);
$method = method_exists($this->jade, 'renderString')
? [$this->jade, 'renderString']
: [$this->jade, 'render'];
return call_user_func($method, $code, $parameters);
}
|
Render a template string.
@param string|\Symfony\Component\Templating\TemplateReferenceInterface $name
@param array $parameters
@throws \ErrorException when a forbidden parameter key is used
@return string
|
entailment
|
public function supports($name)
{
// @codeCoverageIgnoreStart
$extensions = method_exists($this->jade, 'getExtensions')
? $this->jade->getExtensions()
: $this->jade->getOption('extensions');
// @codeCoverageIgnoreEnd
foreach ($extensions as $extension) {
if (substr($name, -strlen($extension)) === $extension) {
return true;
}
}
return false;
}
|
Check if a file extension is supported by Pug.
@param string|\Symfony\Component\Templating\TemplateReferenceInterface $name
@return bool
|
entailment
|
public function getOption($name, $default = null)
{
return method_exists($this->jade, 'hasOption') && !$this->jade->hasOption($name)
? $default
: $this->jade->getOption($name);
}
|
Get a Pug engine option or the default value passed as second parameter (null if omitted).
@deprecated This method has inconsistent behavior depending on which major version of the Pug-php engine you
use, so prefer using getOptionDefault instead that has consistent output no matter the Pug-php
version.
@param string $name
@param mixed $default
@throws \InvalidArgumentException when using Pug-php 2 engine and getting an option not set
@return mixed
|
entailment
|
protected function findTemplate($name, $throw = null)
{
$result = parent::findTemplate($name, false);
if ($result === false) {
return __DIR__.'/../Test/Fixtures/twig/empty.twig';
}
return $result;
}
|
Hacked find template to allow loading templates by absolute path.
@param string $name template name or absolute path
|
entailment
|
protected function newGenerator($type, $length = null)
{
$generator = GeneratorFactory::create($type)->mutate($this)->length($length ?: $this->length);
if (isset($this->prefix)) {
$generator->prefix($this->prefix);
}
if (isset($this->suffix)) {
$generator->suffix($this->suffix);
}
return $generator;
}
|
Creates a new generator instance of the given type.
@param string $type Generator type
@param mixed $length
@return Keygen\Generator
@throws \InvalidArgumentException
|
entailment
|
protected function newGeneratorFromAlias($alias, $length = null)
{
$generatorAliases = [
'numeric' => 'numeric',
'alphanum' => 'alphaNumeric',
'token' => 'token',
'bytes' => 'randomByte'
];
if (array_key_exists($alias, $generatorAliases)) {
return $this->newGenerator($generatorAliases[$alias], $length);
}
}
|
Creates a new generator instance from the given alias.
@param string $alias Generator type alias
@param mixed $length
@return Keygen\Generator | null
@throws \InvalidArgumentException
|
entailment
|
protected function keygen($length)
{
$key = '';
$chars = array_merge(range(0, 9), range('a', 'z'), range(0, 9), range('A', 'Z'), range(0, 9));
shuffle($chars);
$chars = str_shuffle(str_rot13(join('', $chars)));
$split = intval(ceil($length / 5));
$size = strlen($chars);
$splitSize = ceil($size / $split);
$chunkSize = 5 + $splitSize + mt_rand(1, 5);
$chunkArray = array();
$chars = str_shuffle(str_repeat($chars, 2));
$size = strlen($chars);
while ($split != 0) {
$strip = substr($chars, mt_rand(0, $size - $chunkSize), $chunkSize);
array_push($chunkArray, strrev($strip));
$split--;
}
foreach ($chunkArray as $set) {
$modulus = ($length - strlen($key)) % 5;
$adjusted = ($modulus > 0) ? $modulus : 5;
$key .= substr($set, mt_rand(0, strlen($set) - $adjusted), $adjusted);
}
return str_rot13(str_shuffle($key));
}
|
Generates a random key.
@param numeric $length
@return string
|
entailment
|
protected function keygen($length)
{
$token = '';
$tokenlength = round($length * 4 / 3);
for ($i = 0; $i < $tokenlength; ++$i) {
$token .= chr(rand(32,1024));
}
$token = base64_encode(str_shuffle($token));
return substr($token, 0, $length);
}
|
Generates a random key.
@param numeric $length
@return string
|
entailment
|
private static function objectDiffInArrays($array1, $array2)
{
return array_udiff($array1, $array2, function($a, $b) {
if ($a === $b) {
return 0;
} elseif ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
}
});
}
|
Object difference comparator using array_diff callback.
@param array $array1
@param array $array2
@return array
|
entailment
|
public function mutate($objects)
{
$objects = call_user_func_array(array($this, 'flattenArguments'), func_get_args());
$collect = [];
foreach ($objects as $obj) {
if ($obj instanceof AbstractGenerator) {
array_push($collect, $obj);
continue;
}
throw new InvalidArgumentException(sprintf('Mutable objects must be instances of %s.', AbstractGenerator::class));
}
$this->mutates = array_merge(static::objectDiffInArrays($this->mutates, $collect), $collect);
return $this;
}
|
Add mutable generators to the mutates collection
@param mixed $objects
@return $this
@throws \InvalidArgumentException
|
entailment
|
public function dontMutate($objects)
{
$objects = call_user_func_array(array($this, 'flattenArguments'), func_get_args());
$this->mutates = static::objectDiffInArrays($this->mutates, $objects);
return $this;
}
|
Remove generators from the mutates collection
@param mixed $objects
@return $this
|
entailment
|
public static function create($type)
{
$generator = sprintf("Keygen\Generators\%sGenerator", ucfirst($type));
if (class_exists($generator)) {
$generator = new $generator;
if ($generator instanceof Generator) {
return $generator;
}
}
throw new InvalidArgumentException('Cannot create unknown generator type.');
}
|
Create a generator instance from the specified type.
@param string $type Generator type.
@return Keygen\Generator
@throws \InvalidArgumentException
|
entailment
|
protected function keygen($length)
{
$chars = str_shuffle('3759402687094152031368921');
$chars = str_shuffle(str_repeat($chars, ceil($length / strlen($chars))));
return strrev(str_shuffle(substr($chars, mt_rand(0, (strlen($chars) - $length - 1)), $length)));
}
|
Generates a random key.
@param numeric $length
@return string
|
entailment
|
protected function keygen($length)
{
$hex = !is_bool($this->hex) ?: $this->hex;
$bytelength = $hex ? ceil($length / 2) : $length;
if (function_exists('random_bytes')) {
$bytes = random_bytes($bytelength);
}
elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($bytelength);
}
elseif (@file_exists('/dev/urandom') && $bytelength < 100) {
$bytes = file_get_contents('/dev/urandom', false, null, 0, $bytelength);
}
else {
throw new RuntimeException('Cannot generate binary data.');
}
return $hex ? substr(bin2hex($bytes), 0, $length) : $bytes;
}
|
Generates a random key.
@param numeric $length
@return string
@throws \RuntimeException
|
entailment
|
public function generate()
{
$key = call_user_func_array('parent::generate', func_get_args());
if ($this->hex === true) {
$this->hex = false;
}
return $key;
}
|
Outputs a generated key including the prefix and suffix if any.
May also return transformed keys.
@return string
|
entailment
|
protected function flattenArguments()
{
$args = func_get_args();
$flat = [];
foreach ($args as $arg) {
if (is_array($arg)) {
$flat = call_user_func_array(array($this, 'flattenArguments'), array_merge($flat, $arg));
continue;
}
array_push($flat, $arg);
}
return $flat;
}
|
Flattens its arguments array into a simple array.
@return array
|
entailment
|
public function mutable($props)
{
$props = call_user_func_array(array($this, 'flattenArguments'), func_get_args());
$collect = $unknown = [];
foreach ($props as $prop) {
if (!property_exists(AbstractGenerator::class, $prop)) {
array_push($unknown, $prop);
continue;
}
array_push($collect, $prop);
}
if (!empty($unknown)) {
throw new InvalidArgumentException(sprintf("Cannot add unknown %s to mutables collection ('%s').", (count($unknown) > 1) ? 'properties' : 'property', join("', '", $unknown)));
}
$this->mutables = array_merge(array_diff($this->mutables, $collect), $collect);
return $this;
}
|
Add mutable attributes to the mutables collection
@param mixed $props
@return $this
@throws \InvalidArgumentException
|
entailment
|
public function immutable($props)
{
$props = call_user_func_array(array($this, 'flattenArguments'), func_get_args());
$this->mutables = array_diff($this->mutables, $props);
return $this;
}
|
Remove attributes from the mutables collection
@param mixed $props
@return $this
|
entailment
|
protected function propagateMutation($prop, $propagate)
{
$propagate = !is_bool($propagate) ? true : $propagate;
if ($propagate && isset($this->mutates)) {
foreach ($this->mutates as $obj) {
if (in_array($prop, $obj->mutables)) {
call_user_func(array($obj, $prop), $this->{$prop});
}
}
}
return $this;
}
|
Propagates property mutation to listed mutable generators.
@param string $prop
@param bool $propagate
@return $this
|
entailment
|
protected function length($length, $propagate = true)
{
$this->length = $this->intCast($length ?: $this->length);
return $this->propagateMutation('length', $propagate);
}
|
Sets the length of keys to be generated by the generator.
@param numeric $length
@param bool $propagate
@return $this
@throws \InvalidArgumentException
|
entailment
|
protected function affix($affix, $value, $propagate = true)
{
$affixes = ['prefix', 'suffix'];
if (in_array($affix, $affixes)) {
if (is_scalar($value)) {
$this->{$affix} = strval($value);
return $this->propagateMutation($affix, $propagate);
}
throw new InvalidArgumentException("The given {$affix} cannot be converted to a string.");
}
}
|
Affixes string to generated keys.
@param string $affix Affix type (either 'prefix' or 'suffix')
@param string $value
@param bool $propagate
@return $this
@throws \InvalidArgumentException
|
entailment
|
protected function getAdjustedKeyLength()
{
return $this->length - intval(strlen($this->prefix) + strlen($this->suffix));
}
|
Gets the key length less the prefix length and suffix length.
@return int
|
entailment
|
protected function __overloadMethods($method, $args)
{
$_method = strtolower($method);
if (in_array($_method, ['prefix', 'suffix'])) {
return call_user_func_array(array($this, 'affix'), array_merge([$_method], $args));
}
if ($_method == 'length') {
return call_user_func_array(array($this, 'length'), $args);
}
throw new BadMethodCallException(sprintf("Call to unknown method %s::%s()", get_called_class(), $method));
}
|
Overload helper for internal method calls.
@param string $method
@param array $args
@return $this
@throws \BadMethodCallException
|
entailment
|
public function generate()
{
$args = func_get_args();
$useKeyLength = array_shift($args);
if (!is_bool($useKeyLength)) {
array_unshift($args, $useKeyLength);
$useKeyLength = false;
}
$callables = call_user_func_array(array($this, 'flattenArguments'), $args);
$key = $this->keygen($useKeyLength ? $this->length : $this->getAdjustedKeyLength());
while ($callable = current($callables)) {
if (is_callable($callable)) {
$key = call_user_func($callable, $key);
}
next($callables);
}
return sprintf("%s%s%s", $this->prefix, $key, $this->suffix);
}
|
Outputs a generated key including the prefix and suffix if any.
May also return transformed keys.
@return string
|
entailment
|
protected function authenticate()
{
$this->ch = curl_init();
$headers = array(
'Accept-Version: v10',
'Accept: application/json',
);
if (!empty($this->auth_string)) {
$headers[] = 'Authorization: Basic ' . base64_encode($this->auth_string);
}
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($this->ch, $options);
}
|
authenticate function.
Create a cURL instance with authentication headers
@access public
|
entailment
|
protected function setUrl($params)
{
curl_setopt($this->client->ch, CURLOPT_URL, Constants::API_URL . trim($params, '/'));
}
|
setUrl function.
Takes an API request string and appends it to the API url
@access protected
@return void
|
entailment
|
protected function execute($request_type, $form = array())
{
// Set the HTTP request type
curl_setopt($this->client->ch, CURLOPT_CUSTOMREQUEST, $request_type);
// If additional data is delivered, we will send it along with the API request
if (is_array($form) && ! empty($form)) {
curl_setopt($this->client->ch, CURLOPT_POSTFIELDS, $this->httpBuildQuery($form, '', '&'));
}
// Store received headers in temporary memory file, remember sent headers
$fh_header = fopen('php://temp', 'w+');
curl_setopt($this->client->ch, CURLOPT_WRITEHEADER, $fh_header);
curl_setopt($this->client->ch, CURLINFO_HEADER_OUT, true);
// Execute the request
$response_data = curl_exec($this->client->ch);
if (curl_errno($this->client->ch) !== 0) {
// An error occurred
fclose($fh_header);
throw new Exception(curl_error($this->client->ch), curl_errno($this->client->ch));
}
// Grab the headers
$sent_headers = curl_getinfo($this->client->ch, CURLINFO_HEADER_OUT);
rewind($fh_header);
$received_headers = stream_get_contents($fh_header);
fclose($fh_header);
// Retrieve the HTTP response code
$response_code = (int) curl_getinfo($this->client->ch, CURLINFO_HTTP_CODE);
// Return the response object.
return new Response($response_code, $sent_headers, $received_headers, $response_data);
}
|
EXECUTE function.
Performs the prepared API request
@access protected
@param string $request_type
@param array $form
@return Response
|
entailment
|
public function getClass($class)
{
$this->checkClass($class);
if (null === $this->infoClass) {
$infoClass = get_class($this).'Info';
$this->infoClass = new $infoClass();
}
return $this->infoClass->{'get'.str_replace('\\', '', $class).'Class'}();
}
|
Returns the metadata of a class.
@param string $class The class.
@return array The metadata of the class.
@throws \LogicException If the class does not exist in the metadata factory.
|
entailment
|
public function renderToImage(\NMC\ImageWithText\Image $image)
{
// Allocate words to lines
$this->distributeText();
// Calculate maximum potential line width (close enough) in pixels
$maxWidthString = implode('', array_fill(0, $this->width, 'x'));
$maxWidthBoundingBox = imagettfbbox($this->size, 0, $this->font, $maxWidthString);
$maxLineWidth = abs($maxWidthBoundingBox[0] - $maxWidthBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position)
// Calculate each line width in pixels for alignment purposes
for ($j = 0; $j < count($this->lines); $j++) {
// Fetch line
$line =& $this->lines[$j];
// Remove unused lines
if (empty($line['words'])) {
unset($this->lines[$j]);
continue;
}
// Calculate width
$lineText = implode(' ', $line['words']);
$lineBoundingBox = imagettfbbox($this->size, 0, $this->font, $lineText);
$line['width'] = abs($lineBoundingBox[0] - $lineBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position)
$line['text'] = $lineText;
}
// Calculate line offsets
for ($i = 0; $i < count($this->lines); $i++) {
// Fetch line
if (array_key_exists($i, $this->lines)) {
$line =& $this->lines[$i];
// Calculate line width in pixels
$lineBoundingBox = imagettfbbox($this->size, 0, $this->font, $line['text']);
$lineWidth = abs($lineBoundingBox[0] - $lineBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position)
// Calculate line X,Y offsets in pixels
switch ($this->align) {
case 'left':
$offsetX = $this->startX;
$offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i);
break;
case 'center':
$imageWidth = $image->getWidth();
$offsetX = (($maxLineWidth - $lineWidth) / 2) + $this->startX;
$offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i);
break;
case 'right':
$imageWidth = $image->getWidth();
$offsetX = $imageWidth - $line['width'] - $this->startX;
$offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i);
break;
}
// Render text onto image
$image->getImage()->text($line['text'], $offsetX, $offsetY, $this->size, $this->color, 0, $this->font);
}
}
}
|
Render text on image
@param \Intervention\Image\Image $image The image on which the text will be rendered
@api
|
entailment
|
protected function distributeText()
{
// Explode input text on word boundaries
$words = explode(' ', $this->text);
// Fill lines with words, toss exception if exceed available lines
while ($words) {
$tooLong = true;
$word = array_shift($words);
for ($i = 0; $i < count($this->lines); $i++) {
$line =& $this->lines[$i];
if ($line['full'] === false) {
$charsPotential = strlen($word) + $line['chars'];
if ($charsPotential <= $this->width) {
array_push($line['words'], $word);
$line['chars'] = $charsPotential;
$tooLong = false;
break;
} else {
$line['full'] = true;
}
}
}
}
// Throw if too long
if ($tooLong === true) {
throw new \Exception('Text is too long');
}
}
|
Distribute text to lines
@throws \Exception If text is too long given available lines and max character width
|
entailment
|
public function toMongo($value)
{
if ($value instanceof \DateTime) {
$value = $value->getTimestamp();
} elseif (is_string($value)) {
$value = strtotime($value);
}
return new \MongoDate($value);
}
|
{@inheritdoc}
|
entailment
|
public function delete($id)
{
$this->time->start();
$return = parent::delete($id);
$time = $this->time->stop();
$this->log(array(
'type' => 'delete',
'id' => $id,
'time' => $time,
));
return $return;
}
|
delete.
|
entailment
|
public function get($id)
{
$this->time->start();
$return = parent::get($id);
$time = $this->time->stop();
$this->log(array(
'type' => 'get',
'id' => $id,
'time' => $time,
));
return $return;
}
|
get.
|
entailment
|
public function put($filename, array $extra = array())
{
$this->time->start();
$return = parent::put($filename, $extra);
$time = $this->time->stop();
$this->log(array(
'type' => 'put',
'filename' => $filename,
'extra' => $extra,
'time' => $time,
));
}
|
put.
|
entailment
|
public function storeBytes($bytes, array $extra, array $options = array())
{
$this->time->start();
$return = parent::storeBytes($bytes, $extra, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'storeBytes',
'bytes_sha1' => sha1($bytes),
'extra' => $extra,
'options' => $options,
'time' => $time,
));
return $return;
}
|
storeBytes.
|
entailment
|
public function storeFile($filename, array $extra, array $options = array())
{
$this->time->start();
$return = parent::storeFile($filename, $extra, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'storeFile',
'filename' => $filename,
'extra' => $extra,
'options' => $options,
'time' => $time,
));
return $return;
}
|
storeFile.
|
entailment
|
public function storeUpload($name, $filename)
{
$this->time->start();
$return = parent::storeUpload($name, $filename);
$time = $this->time->stop();
$this->log(array(
'type' => 'storeUpload',
'name' => $name,
'filename' => $filename,
'time' => $time,
));
return $return;
}
|
storeUpload.
|
entailment
|
public function count($query = array(), $limit = 0, $skip = 0)
{
$this->time->start();
$return = parent::count($query, $limit, $skip);
$time = $this->time->stop();
$this->log(array(
'type' => 'count',
'query' => $query,
'limit' => $limit,
'skip' => $skip,
'time' => $time,
));
return $return;
}
|
count.
|
entailment
|
public function deleteIndex($keys)
{
$this->time->start();
$return = parent::deleteIndex($keys);
$time = $this->time->stop();
$this->log(array(
'type' => 'deleteIndex',
'keys' => $keys,
'time' => $time,
));
return $return;
}
|
deleteIndex.
|
entailment
|
public function deleteIndexes()
{
$this->time->start();
$return = parent::deleteIndexes();
$time = $this->time->stop();
$this->log(array(
'type' => 'deleteIndexes',
'time' => $time,
));
return $return;
}
|
deleteIndexes.
|
entailment
|
public function drop()
{
$this->time->start();
$return = parent::drop();
$time = $this->time->stop();
$this->log(array(
'type' => 'drop',
'time' => $time,
));
return $return;
}
|
drop.
|
entailment
|
public function ensureIndex($keys, array $options = array())
{
$this->time->start();
$return = parent::ensureIndex($keys, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'ensureIndex',
'keys' => $keys,
'options' => $options,
'time' => $time,
));
return $return;
}
|
ensureIndex.
|
entailment
|
public function findOne($query = array(), $fields = array())
{
$cursor = new LoggableMongoGridFSCursor($this, $query, $fields, 'findOne');
$cursor->limit(-1);
return $cursor->getNext();
}
|
/*
findOne.
|
entailment
|
public function getDBRef($ref)
{
$this->time->start();
$return = parent::getDBRef($ref);
$time = $this->time->stop();
$this->log(array(
'type' => 'getDBRef',
'ref' => $ref,
'time' => $time,
));
return $return;
}
|
getDBRef.
|
entailment
|
public function getIndexInfo()
{
$this->time->start();
$return = parent::getIndexInfo();
$time = $this->time->stop();
$this->log(array(
'type' => 'getIndexInfo',
'time' => $time,
));
return $return;
}
|
getIndexInfo.
|
entailment
|
public function group($keys, $initial, $reduce, array $options = array())
{
$this->time->start();
$return = parent::group($keys, $initial, $reduce, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'group',
'keys' => $keys,
'initial' => $initial,
'reduce' => $reduce,
'options' => $options,
'time' => $time,
));
return $return;
}
|
group.
|
entailment
|
public function insert($a, array $options = array())
{
$this->time->start();
$return = parent::insert($a, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'insert',
'a' => $a,
'options' => $options,
'time' => $time,
));
return $return;
}
|
insert.
|
entailment
|
public function remove($criteria = array(), array $options = array())
{
$this->time->start();
$return = parent::remove($criteria, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'remove',
'criteria' => $criteria,
'options' => $options,
'time' => $time,
));
return $return;
}
|
remove.
|
entailment
|
public function update($criteria, $newobj, array $options = array())
{
$this->time->start();
$return = parent::update($criteria, $newobj, $options);
$time = $this->time->stop();
$this->log(array(
'type' => 'update',
'criteria' => $criteria,
'newobj' => $newobj,
'options' => $options,
'time' => $time,
));
return $return;
}
|
update.
|
entailment
|
public function validate($scanData = false)
{
$this->time->start();
$return = parent::validate($scanData);
$time = $this->time->stop();
$this->log(array(
'type' => 'validate',
'scanData' => $scanData,
'time' => $time,
));
return $return;
}
|
validate.
|
entailment
|
public function log(array $log)
{
if ($this->loggerCallable) {
call_user_func($this->loggerCallable, array_merge($this->logDefault, $log));
}
}
|
Log.
@param array $log The log value.
|
entailment
|
public function count($foundOnly = false)
{
$this->time->start();
$return = parent::count($foundOnly);
$time = $this->time->stop();
$info = $this->info();
$this->log(array(
'type' => 'count',
'query' => is_array($info['query']) ? $info['query'] : array(),
'limit' => $info['limit'],
'skip' => $info['skip'],
'foundOnly' => $foundOnly,
'time' => $time,
));
return $return;
}
|
/*
count.
|
entailment
|
protected function logQuery()
{
$info = $this->info();
if (!$info['started_iterating']) {
if (!is_array($info['query'])) {
$info['query'] = array();
} else if (!isset($info['query']['$query'])) {
$info['query'] = array('$query' => $info['query']);
}
// explain cursor
$this->explainCursor->fields($info['fields']);
$this->explainCursor->limit($info['limit']);
$this->explainCursor->skip($info['skip']);
if (isset($info['batchSize'])) {
$this->explainCursor->batchSize($info['batchSize']);
}
if (isset($info['query']['$orderby'])) {
$this->explainCursor->sort($info['query']['$orderby']);
}
if (isset($info['query']['$hint'])) {
$this->explainCursor->hint($info['query']['$hint']);
}
if (isset($info['query']['$snapshot'])) {
$this->explainCursor->snapshot();
}
$explain = $this->explainCursor->explain();
// log
$log = array(
'type' => $this->type,
'query' => isset($info['query']['$query']) && is_array($info['query']['$query']) ? $info['query']['$query'] : array(),
'fields' => $info['fields'],
);
if (isset($info['query']['$orderby'])) {
$log['sort'] = $info['query']['$orderby'];
}
if ($info['limit']) {
$log['limit'] = $info['limit'];
}
if ($info['skip']) {
$log['skip'] = $info['skip'];
}
if ($info['batchSize']) {
$log['batchSize'] = $info['batchSize'];
}
if (isset($info['query']['$hint'])) {
$log['hint'] = $info['query']['$hint'];
}
if (isset($info['query']['$snapshot'])) {
$log['snapshot'] = 1;
}
$log['explain'] = array(
'nscanned' => $explain['nscanned'],
'nscannedObjects' => $explain['nscannedObjects'],
'n' => $explain['n'],
'indexBounds' => $explain['indexBounds'],
);
$log['time'] = $explain['millis'];
$this->log($log);
}
}
|
/*
log the query.
|
entailment
|
public function refresh()
{
if ($this->isNew()) {
throw new \LogicException('The document is new.');
}
$this->setDocumentData($this->getRepository()->getCollection()->findOne(array('_id' => $this->getId())), true);
return $this;
}
|
Refresh the document data from the database.
@return \Mandango\Document\Document The document (fluent interface).
@throws \LogicException
@api
|
entailment
|
public function removeQueryHash($hash)
{
$queryHashes =& Archive::getByRef($this, 'query_hashes', array());
unset($queryHashes[array_search($hash, $queryHashes)]);
$queryHashes = array_values($queryHashes);
}
|
Removes a query hash.
@param string $hash The query hash.
|
entailment
|
public function addFieldCache($field)
{
$cache = $this->getMandango()->getCache();
foreach ($this->getQueryHashes() as $hash) {
$value = $cache->has($hash) ? $cache->get($hash) : array();
$value['fields'][$field] = 1;
$cache->set($hash, $value);
}
}
|
Add a field cache.
|
entailment
|
public function addReferenceCache($reference)
{
$cache = $this->getMandango()->getCache();
foreach ($this->getQueryHashes() as $hash) {
$value = $cache->has($hash) ? $cache->get($hash) : array();
if (!isset($value['references']) || !in_array($reference, $value['references'])) {
$value['references'][] = $reference;
$cache->set($hash, $value);
}
}
}
|
Adds a reference cache
|
entailment
|
protected function doNewClassExtensionsProcess()
{
// default behaviors
foreach ($this->getOption('default_behaviors') as $behavior) {
if (!empty($configClass['isEmbedded']) && !empty($behavior['not_with_embeddeds'])) {
continue;
}
$this->newClassExtensions[] = $this->createClassExtensionFromArray($behavior);
}
// class behaviors
if (isset($this->configClass['behaviors'])) {
foreach ($this->configClass['behaviors'] as $behavior) {
$this->newClassExtensions[] = $this->createClassExtensionFromArray($behavior);
}
}
}
|
{@inheritdoc}
|
entailment
|
protected function doConfigClassProcess()
{
$this->initIsEmbeddedProcess();
$this->initInheritableProcess();
$this->initInheritanceProcess();
$this->initMandangoProcess();
if (!$this->configClass['isEmbedded']) {
$this->initUseBatchInsertProcess();
$this->initConnectionNameProcess();
$this->initCollectionNameProcess();
}
$this->initIndexesProcess();
$this->initFieldsProcess();
$this->initReferencesProcess();
$this->initEmbeddedsProcess();
if (!$this->configClass['isEmbedded']) {
$this->initRelationsProcess();
}
$this->initEventsProcess();
$this->initOnDeleteProcess();
$this->initIsFileProcess();
}
|
{@inheritdoc}
|
entailment
|
protected function doClassProcess()
{
// parse and check
if (!$this->configClass['isEmbedded']) {
$this->parseAndCheckIdGeneratorProcess();
}
$this->parseAndCheckFieldsProcess();
$this->parseAndCheckReferencesProcess();
$this->parseAndCheckEmbeddedsProcess();
if (!$this->configClass['isEmbedded']) {
$this->parseAndCheckRelationsProcess();
}
$this->checkDataNamesProcess();
$this->parseOnDeleteProcess();
// definitions
$this->initDefinitionsProcess();
// document
$templates = array(
'DocumentInitializeDefaults',
'DocumentSetDocumentData',
'DocumentFields',
'DocumentReferencesOne',
'DocumentReferencesMany',
'DocumentProcessOnDelete',
);
if ($this->configClass['_has_references']) {
$templates[] = 'DocumentUpdateReferenceFields';
$templates[] = 'DocumentSaveReferences';
}
$templates[] = 'DocumentEmbeddedsOne';
$templates[] = 'DocumentEmbeddedsMany';
if (!$this->configClass['isEmbedded']) {
$templates[] = 'DocumentRelations';
}
if ($this->configClass['_has_groups']) {
$templates[] = 'DocumentResetGroups';
}
$templates[] = 'DocumentSetGet';
$templates[] = 'DocumentFromToArray';
$templates[] = 'DocumentEventsMethods';
$templates[] = 'DocumentQueryForSave';
foreach ($templates as $template) {
$this->processTemplate($this->definitions['document_base'], file_get_contents(__DIR__.'/templates/Core/'.$template.'.php.twig'));
}
if (!$this->configClass['isEmbedded']) {
// repository
$this->processTemplate($this->definitions['repository_base'], file_get_contents(__DIR__.'/templates/Core/Repository.php.twig'));
// query
$this->processTemplate($this->definitions['query_base'], file_get_contents(__DIR__.'/templates/Core/Query.php.twig'));
}
}
|
{@inheritdoc}
|
entailment
|
protected function doPreGlobalProcess()
{
$this->globalInheritableAndInheritanceProcess();
$this->globalHasReferencesProcess();
$this->globalOnDeleteProcess();
$this->globalHasGroupsProcess();
$this->globalIndexesProcess();
}
|
{@inheritdoc}
|
entailment
|
private function initInheritableProcess()
{
if (!isset($this->configClass['inheritable'])) {
$this->configClass['inheritable'] = false;
} elseif ($this->configClass['isEmbedded']) {
throw new \RuntimeException(sprintf('Using unheritance in a embedded document "%s".', $this->class));
}
}
|
/*
configClass
|
entailment
|
private function parseAndCheckIdGeneratorProcess()
{
if (!isset($this->configClass['idGenerator'])) {
$this->configClass['idGenerator'] = 'native';
}
if (!is_array($this->configClass['idGenerator'])) {
if (!is_string($this->configClass['idGenerator'])) {
throw new \RuntimeException(sprintf('The idGenerator of the class "%s" is not neither an array nor a string.', $this->class));
}
$this->configClass['idGenerator'] = array('name' => $this->configClass['idGenerator']);
}
if (!isset($this->configClass['idGenerator']['options'])) {
$this->configClass['idGenerator']['options'] = array();
} elseif (!is_array($this->configClass['idGenerator']['options'])) {
throw new \RuntimeException(sprintf('The options key of the idGenerator of the class "%s" is not an array.', $this->class));
}
if (!IdGeneratorContainer::has($this->configClass['idGenerator']['name'])) {
throw new \RuntimeException(sprintf('The id generator "%s" of the class "%s" does not exist.', $this->configClass['idGenerator']['name'], $this->class));
}
}
|
/*
class
|
entailment
|
private function globalInheritableAndInheritanceProcess()
{
// inheritable
foreach ($this->configClasses as $class => &$configClass) {
if ($configClass['inheritable']) {
if (!is_array($configClass['inheritable'])) {
throw new \RuntimeException(sprintf('The inheritable configuration of the class "%s" is not an array.', $class));
}
if (!isset($configClass['inheritable']['type'])) {
throw new \RuntimeException(sprintf('The inheritable configuration of the class "%s" does not have type.', $class));
}
if (!in_array($configClass['inheritable']['type'], array('single'))) {
throw new \RuntimeException(sprintf('The inheritable type "%s" of the class "%s" is not valid.', $configClass['inheritable']['type'], $class));
}
if ('single' == $configClass['inheritable']['type']) {
if (!isset($configClass['inheritable']['field'])) {
$configClass['inheritable']['field'] = 'type';
}
$configClass['inheritable']['values'] = array();
}
}
}
// inheritance
foreach ($this->configClasses as $class => &$configClass) {
if (!$configClass['inheritance']) {
$configClass['_parent_events'] = array(
'preInsert' => array(),
'postInsert' => array(),
'preUpdate' => array(),
'postUpdate' => array(),
'preDelete' => array(),
'postDelete' => array(),
);
continue;
}
if (!isset($configClass['inheritance']['class'])) {
throw new \RuntimeException(sprintf('The inheritable configuration of the class "%s" does not have class.', $class));
}
$inheritanceClass = $configClass['inheritance']['class'];
// inherited
$inheritedFields = $this->configClasses[$inheritanceClass]['fields'];
$inheritedReferencesOne = $this->configClasses[$inheritanceClass]['referencesOne'];
$inheritedReferencesMany = $this->configClasses[$inheritanceClass]['referencesMany'];
$inheritedEmbeddedsOne = $this->configClasses[$inheritanceClass]['embeddedsOne'];
$inheritedEmbeddedsMany = $this->configClasses[$inheritanceClass]['embeddedsMany'];
// inheritable
if ($this->configClasses[$inheritanceClass]['inheritable']) {
$inheritableClass = $inheritanceClass;
$inheritable = $this->configClasses[$inheritanceClass]['inheritable'];
} elseif ($this->configClasses[$inheritanceClass]['inheritance']) {
$parentInheritance = $this->configClasses[$inheritanceClass]['inheritance'];
do {
$continueSearchingInheritable = false;
// inherited
$inheritedFields = array_merge($inheritedFields, $this->configClasses[$parentInheritance['class']]['fields']);
$inheritedReferencesOne = array_merge($inheritedReferencesOne, $this->configClasses[$parentInheritance['class']]['referencesOne']);
$inheritedReferencesMany = array_merge($inheritanceReferencesMany, $this->configClasses[$parentInheritance['class']]['referencesMany']);
$inheritedEmbeddedsOne = array_merge($inheritedEmbeddedsOne, $this->configClasses[$parentInheritance['class']]['embeddedsOne']);
$inheritedEmbeddedsMany = array_merge($inheritedEmbeddedsMany, $this->configClasses[$parentInheritance['class']]['embeddedsMany']);
if ($this->configClasses[$parentInheritance['class']]['inheritable']) {
$inheritableClass = $parentInheritance['class'];
$inheritable = $this->configClasses[$parentInheritance['class']]['inheritable'];
} else {
$continueSearchingInheritance = true;
$parentInheritance = $this->configClasses[$parentInheritance['class']]['inheritance'];
}
} while ($continueSearchingInheritable);
} else {
throw new \RuntimeException(sprintf('The class "%s" is not inheritable or has inheritance.', $configClass['inheritance']['class']));
}
// inherited fields
foreach ($inheritedFields as $name => &$field) {
if (is_string($field)) {
$field = array('type' => $field);
}
$field['inherited'] = true;
}
unset($field);
$configClass['fields'] = array_merge($inheritedFields, $configClass['fields']);
// inherited referencesOne
foreach ($inheritedReferencesOne as $name => &$referenceOne) {
$referenceOne['inherited'] = true;
}
unset($referenceOne);
$configClass['referencesOne'] = array_merge($inheritedReferencesOne, $configClass['referencesOne']);
$configClass['inheritance']['type'] = $inheritable['type'];
// inherited referencesMany
foreach ($inheritedReferencesMany as $name => &$referenceMany) {
$referenceMany['inherited'] = true;
}
unset($referenceMany);
$configClass['referencesMany'] = array_merge($inheritedReferencesMany, $configClass['referencesMany']);
// inherited embeddedsOne
foreach ($inheritedEmbeddedsOne as $name => &$embeddedOne) {
$embeddedOne['inherited'] = true;
}
unset($embeddedOne);
$configClass['embeddedsOne'] = array_merge($inheritedEmbeddedsOne, $configClass['embeddedsOne']);
// inherited embeddedsMany
foreach ($inheritedEmbeddedsMany as $name => &$embeddedMany) {
$embeddedMany['inherited'] = true;
}
unset($embeddedMany);
$configClass['embeddedsMany'] = array_merge($inheritedEmbeddedsMany, $configClass['embeddedsMany']);
// id generator (always the same as the last parent)
$loopClass = $inheritableClass;
do {
if ($this->configClasses[$loopClass]['inheritance']) {
$loopClass = $this->configClasses[$loopClass]['inheritance']['class'];
$continue = true;
} else {
if (isset($this->configClasses[$loopClass]['idGenerator'])) {
$configClass['idGenerator'] = $this->configClasses[$loopClass]['idGenerator'];
}
$continue = false;
}
} while($continue);
// parent events
$parentEvents = array(
'preInsert' => array(),
'postInsert' => array(),
'preUpdate' => array(),
'postUpdate' => array(),
'preDelete' => array(),
'postDelete' => array(),
);
$loopClass = $inheritableClass;
do {
$parentEvents = array_merge_recursive($this->configClasses[$loopClass]['events'], $parentEvents);
if ($this->configClasses[$loopClass]['inheritance']) {
$loopClass = $this->configClasses[$loopClass]['inheritance']['class'];
$continue = true;
} else {
$continue = false;
}
} while ($continue);
$configClass['_parent_events'] = $parentEvents;
// type
if ('single' == $inheritable['type']) {
//single inheritance does not work with multiple inheritance
if (!$this->configClasses[$configClass['inheritance']['class']]['inheritable']) {
throw new \RuntimeException(sprintf('The single inheritance does not work with multiple inheritance (%s).', $class));
}
if (!isset($configClass['inheritance']['value'])) {
throw new \RuntimeException(sprintf('The inheritance configuration in the class "%s" does not have value.', $class));
}
$value = $configClass['inheritance']['value'];
if (isset($this->configClasses[$inheritableClass]['inheritable']['values'][$value])) {
throw new \RuntimeException(sprintf('The value "%s" is in the single inheritance of the class "%s" more than once.', $value, $inheritanceClass));
}
$this->configClasses[$inheritableClass]['inheritable']['values'][$value] = $class;
if (isset($this->configClasses[$inheritableClass]['inheritance']['class'])) {
$grandParentClass = $this->configClasses[$inheritableClass]['inheritance']['class'];
$this->configClasses[$grandParentClass]['inheritable']['values'][$value] = $class;
}
$configClass['collection'] = $this->configClasses[$inheritableClass]['collection'];
$configClass['inheritance']['field'] = $inheritable['field'];
}
}
}
|
/*
preGlobal
|
entailment
|
private function globalMetadataProcess()
{
$output = new Output($this->getOption('metadata_factory_output'), true);
$definition = new Definition($this->getOption('metadata_factory_class'), $output);
$definition->setParentClass('\Mandango\MetadataFactory');
$this->definitions['metadata_factory'] = $definition;
$output = new Output($this->getOption('metadata_factory_output'), true);
$definition = new Definition($this->getOption('metadata_factory_class').'Info', $output);
$this->definitions['metadata_factory_info'] = $definition;
$classes = array();
foreach ($this->configClasses as $class => $configClass) {
$classes[$class] = $configClass['isEmbedded'];
$info = array();
// general
$info['isEmbedded'] = $configClass['isEmbedded'];
if (!$info['isEmbedded']) {
$info['mandango'] = $configClass['mandango'];
$info['connection'] = $configClass['connection'];
$info['collection'] = $configClass['collection'];
}
// inheritable
$info['inheritable'] = $configClass['inheritable'];
// inheritance
$info['inheritance'] = $configClass['inheritance'];
// fields
$info['fields'] = $configClass['fields'];
// references
$info['_has_references'] = $configClass['_has_references'];
$info['referencesOne'] = $configClass['referencesOne'];
$info['referencesMany'] = $configClass['referencesMany'];
// embeddeds
$info['embeddedsOne'] = $configClass['embeddedsOne'];
$info['embeddedsMany'] = $configClass['embeddedsMany'];
// relations
if (!$info['isEmbedded']) {
$info['relationsOne'] = $configClass['relationsOne'];
$info['relationsManyOne'] = $configClass['relationsManyOne'];
$info['relationsManyMany'] = $configClass['relationsManyMany'];
$info['relationsManyThrough'] = $configClass['relationsManyThrough'];
}
// indexes
$info['indexes'] = $configClass['indexes'];
$info['_indexes'] = $configClass['_indexes'];
$info = \Mandango\Mondator\Dumper::exportArray($info, 12);
$method = new Method('public', 'get'.str_replace('\\', '', $class).'Class', '', <<<EOF
return $info;
EOF
);
$this->definitions['metadata_factory_info']->addMethod($method);
}
$property = new Property('protected', 'classes', $classes);
$this->definitions['metadata_factory']->addProperty($property);
}
|
/*
postGlobal
|
entailment
|
public function isModified()
{
if (isset($this->data['fields'])) {
foreach ($this->data['fields'] as $name => $value) {
if ($this->isFieldModified($name)) {
return true;
}
}
}
if (isset($this->data['embeddedsOne'])) {
foreach ($this->data['embeddedsOne'] as $name => $embedded) {
if ($embedded && $embedded->isModified()) {
return true;
}
if ($this->isEmbeddedOneChanged($name)) {
$root = null;
if ($this instanceof Document) {
$root = $this;
} elseif ($rap = $this->getRootAndPath()) {
$root = $rap['root'];
}
if ($root && !$root->isNew()) {
return true;
}
}
}
}
if (isset($this->data['embeddedsMany'])) {
foreach ($this->data['embeddedsMany'] as $name => $group) {
foreach ($group->getAdd() as $document) {
if ($document->isModified()) {
return true;
}
}
$root = null;
if ($this instanceof Document) {
$root = $this;
} elseif ($rap = $this->getRootAndPath()) {
$root = $rap['root'];
}
if ($root && !$root->isNew()) {
if ($group->getRemove()) {
return true;
}
}
if ($group->isSavedInitialized()) {
foreach ($group->getSaved() as $document) {
if ($document->isModified()) {
return true;
}
}
}
}
}
return false;
}
|
Returns if the document is modified.
@return bool If the document is modified.
@api
|
entailment
|
public function clearModified()
{
if (isset($this->data['fields'])) {
$this->clearFieldsModified();
}
if (isset($this->data['embeddedsOne'])) {
$this->clearEmbeddedsOneChanged();
foreach ($this->data['embeddedsOne'] as $name => $embedded) {
if ($embedded) {
$embedded->clearModified();
}
}
}
if (isset($this->data['embeddedsMany'])) {
foreach ($this->data['embeddedsMany'] as $name => $group) {
$group->clearAdd();
$group->clearRemove();
$group->clearSaved();
}
}
}
|
Clear the document modifications, that is, they will not be modifications apart from here.
@api
|
entailment
|
public function isFieldModified($name)
{
return isset($this->fieldsModified[$name]) || array_key_exists($name, $this->fieldsModified);
}
|
Returns if a field is modified.
@param string $name The field name.
@return bool If the field is modified.
@api
|
entailment
|
public function getOriginalFieldValue($name)
{
if ($this->isFieldModified($name)) {
return $this->fieldsModified[$name];
}
if (isset($this->data['fields'][$name])) {
return $this->data['fields'][$name];
}
return null;
}
|
Returns the original value of a field.
@param string $name The field name.
@return mixed The original value of the field.
@api
|
entailment
|
public function isEmbeddedOneChanged($name)
{
if (!isset($this->data['embeddedsOne'])) {
return false;
}
if (!isset($this->data['embeddedsOne'][$name]) && !array_key_exists($name, $this->data['embeddedsOne'])) {
return false;
}
return Archive::has($this, 'embedded_one.'.$name);
}
|
Returns if an embedded one is changed.
@param string $name The embedded one name.
@return bool If the embedded one is modified.
@api
|
entailment
|
public function getOriginalEmbeddedOneValue($name)
{
if (Archive::has($this, 'embedded_one.'.$name)) {
return Archive::get($this, 'embedded_one.'.$name);
}
if (isset($this->data['embeddedsOne'][$name])) {
return $this->data['embeddedsOne'][$name];
}
return null;
}
|
Returns the original value of an embedded one.
@param string $name The embedded one name.
@return mixed The embedded one original value.
@api
|
entailment
|
public function getEmbeddedsOneChanged()
{
$embeddedsOneChanged = array();
if (isset($this->data['embeddedsOne'])) {
foreach ($this->data['embeddedsOne'] as $name => $embedded) {
if ($this->isEmbeddedOneChanged($name)) {
$embeddedsOneChanged[$name] = $this->getOriginalEmbeddedOneValue($name);
}
}
}
return $embeddedsOneChanged;
}
|
Returns an array with the embedded ones changed, with the embedded name as key and the original embedded value as value.
@return array An array with the embedded ones changed.
@api
|
entailment
|
public function debug()
{
$info = array();
$metadata = $this->getMetadata();
$referenceFields = array();
foreach (array_merge($metadata['referencesOne'], $metadata['referencesMany']) as $name => $reference) {
$referenceFields[] = $reference['field'];
}
// fields
foreach ($metadata['fields'] as $name => $field) {
if (in_array($name, $referenceFields)) {
continue;
}
$info['fields'][$name] = $this->{'get'.ucfirst($name)}();
}
// referencesOne
foreach ($metadata['referencesOne'] as $name => $referenceOne) {
$info['referencesOne'][$name] = $this->{'get'.ucfirst($referenceOne['field'])}();
}
// referencesMany
foreach ($metadata['referencesMany'] as $name => $referenceMany) {
$info['referencesMany'][$name] = $this->{'get'.ucfirst($referenceMany['field'])}();
}
// embeddedsOne
foreach ($metadata['embeddedsOne'] as $name => $embeddedOne) {
$embedded = $this->{'get'.ucfirst($name)}();
$info['embeddedsOne'][$name] = $embedded ? $embedded->debug() : null;
}
// embeddedsMany
foreach ($metadata['embeddedsMany'] as $name => $embeddedMany) {
$info['embeddedsMany'][$name] = array();
foreach ($this->{'get'.ucfirst($name)}() as $key => $value) {
$info['embeddedsMany'][$name][$key] = $value->debug();
}
}
return $info;
}
|
Returns an array with the document info to debug.
@return array An array with the document info.
|
entailment
|
static public function has($object, $key)
{
$oid = spl_object_hash($object);
return isset(static::$archive[$oid]) && (isset(static::$archive[$oid][$key]) || array_key_exists($key, static::$archive[$oid]));
}
|
Returns if an object has a key in the archive.
@param object $object The object.
@param string $key The key.
@return bool If an object has a key in the archive.
|
entailment
|
static public function &getByRef($object, $key, $default = null)
{
$oid = spl_object_hash($object);
if (!isset(static::$archive[$oid][$key])) {
static::$archive[$oid][$key] = $default;
}
return static::$archive[$oid][$key];
}
|
Returns an object key by reference. It creates the key if the key does not exist.
@param object $object The object
@param string $key The key.
@param mixed $default The default value, used to create the key if it does not exist (null by default).
@return mixed The object key value.
|
entailment
|
static public function getOrDefault($object, $key, $default)
{
$oid = spl_object_hash($object);
if (isset(static::$archive[$oid]) && (isset(static::$archive[$oid][$key]) || array_key_exists($key, static::$archive[$oid]))) {
return static::$archive[$oid][$key];
}
return $default;
}
|
Returns an object key or returns a default value otherwise.
@param object $object The object.
@param string $key The key.
@param mixed $default The value to return if the object key does not exist.
@return mixed The object key value or the default value.
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.