code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function set($model, $key, $value, $attributes)
{
if (! $value instanceof AddressModel) {
throw new InvalidArgumentException('The given value is not an Address instance.');
}
return [
'address_line_one' => $value->lineOne,
'address_line_two' => $value->lineTwo,
];
} | Prepare the given value for storage.
@param \Illuminate\Database\Eloquent\Model $model
@param string $key
@param AddressModel $value
@param array $attributes
@return array | set | php | laravel/framework | tests/Database/EloquentModelCustomCastingTest.php | https://github.com/laravel/framework/blob/master/tests/Database/EloquentModelCustomCastingTest.php | MIT |
public function set($model, $key, $value, $attributes)
{
return gmp_strval($value, 10);
} | Prepare the given value for storage.
@param \Illuminate\Database\Eloquent\Model $model
@param string $key
@param string|null $value
@param array $attributes
@return string | set | php | laravel/framework | tests/Database/EloquentModelCustomCastingTest.php | https://github.com/laravel/framework/blob/master/tests/Database/EloquentModelCustomCastingTest.php | MIT |
public function serialize($model, string $key, $value, array $attributes)
{
return gmp_strval($value, 10);
} | Serialize the attribute when converting the model to an array.
@param \Illuminate\Database\Eloquent\Model $model
@param string $key
@param mixed $value
@param array $attributes
@return mixed | serialize | php | laravel/framework | tests/Database/EloquentModelCustomCastingTest.php | https://github.com/laravel/framework/blob/master/tests/Database/EloquentModelCustomCastingTest.php | MIT |
protected function migrateDefault()
{
$this->schema()->create('users_default', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->unsignedInteger('has_many_through_default_test_country_id');
$table->timestamps();
});
$this->schema()->create('posts_default', function ($table) {
$table->increments('id');
$table->integer('has_many_through_default_test_user_id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
$this->schema()->create('countries_default', function ($table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
} | Migrate tables for classes with a Laravel "default" HasManyThrough setup. | migrateDefault | php | laravel/framework | tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php | https://github.com/laravel/framework/blob/master/tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php | MIT |
public function __construct($message = null, $code = null)
{
$this->message = $message;
$this->code = $code;
} | Overrides Exception::__construct, which casts $code to integer, so that we can create
an exception with a string $code consistent with the real PDOException behavior.
@param string|null $message
@param string|null $code
@return void | __construct | php | laravel/framework | tests/Database/DatabaseConnectionTest.php | https://github.com/laravel/framework/blob/master/tests/Database/DatabaseConnectionTest.php | MIT |
protected function migrateDefault()
{
$this->schema()->create('users_default', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->unsignedInteger('has_one_through_default_test_position_id')->unique()->nullable();
$table->timestamps();
});
$this->schema()->create('contracts_default', function ($table) {
$table->increments('id');
$table->integer('has_one_through_default_test_user_id')->unique();
$table->string('title');
$table->text('body');
$table->timestamps();
});
$this->schema()->create('positions_default', function ($table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
} | Migrate tables for classes with a Laravel "default" HasOneThrough setup. | migrateDefault | php | laravel/framework | tests/Database/DatabaseEloquentHasOneThroughIntegrationTest.php | https://github.com/laravel/framework/blob/master/tests/Database/DatabaseEloquentHasOneThroughIntegrationTest.php | MIT |
protected function assertHasMiddleware($controller, $method, $middleware)
{
$router = new Router(new Dispatcher);
$router->aliasMiddleware('can', AuthorizesResourcesMiddleware::class);
$router->get($method)->uses(get_class($controller).'@'.$method);
$this->assertSame(
'caught '.$middleware,
$router->dispatch(Request::create($method, 'GET'))->getContent(),
"The [{$middleware}] middleware was not registered for method [{$method}]"
);
} | Assert that the given middleware has been registered on the given controller for the given method.
@param \Illuminate\Routing\Controller $controller
@param string $method
@param string $middleware
@return void | assertHasMiddleware | php | laravel/framework | tests/Auth/AuthorizesResourcesTest.php | https://github.com/laravel/framework/blob/master/tests/Auth/AuthorizesResourcesTest.php | MIT |
protected function gate()
{
return $this->container->make(GateContract::class);
} | Get the Gate instance from the container.
@return \Illuminate\Auth\Access\Gate | gate | php | laravel/framework | tests/Auth/AuthorizeMiddlewareTest.php | https://github.com/laravel/framework/blob/master/tests/Auth/AuthorizeMiddlewareTest.php | MIT |
public static function collectionClassProvider()
{
return [
[Collection::class],
[LazyCollection::class],
];
} | Provides each collection class, respectively.
@return array | collectionClassProvider | php | laravel/framework | tests/Support/SupportCollectionTest.php | https://github.com/laravel/framework/blob/master/tests/Support/SupportCollectionTest.php | MIT |
public function connect(array $config, array $options)
{
return 'my-redis-connection';
} | Create a new clustered Predis connection.
@param array $config
@param array $options
@return string | connect | php | laravel/framework | tests/Redis/RedisManagerExtensionTest.php | https://github.com/laravel/framework/blob/master/tests/Redis/RedisManagerExtensionTest.php | MIT |
public function connectToCluster(array $config, array $clusterOptions, array $options)
{
return 'my-redis-cluster-connection';
} | Create a new clustered Predis connection.
@param array $config
@param array $clusterOptions
@param array $options
@return string | connectToCluster | php | laravel/framework | tests/Redis/RedisManagerExtensionTest.php | https://github.com/laravel/framework/blob/master/tests/Redis/RedisManagerExtensionTest.php | MIT |
public function via($notifiable)
{
return 'mail';
} | Get the notification channels.
@param mixed $notifiable
@return array|string | via | php | laravel/framework | tests/Notifications/NotificationSenderTest.php | https://github.com/laravel/framework/blob/master/tests/Notifications/NotificationSenderTest.php | MIT |
private function transform($value)
{
/*
* Casts carbon instances to timestamp.
*/
if ($value instanceof \Illuminate\Support\Carbon) {
$value = $value->getTimestamp();
}
return $value;
} | Transform the given where value.
@param mixed $value
@return mixed | transform | php | algolia/scout-extended | src/Builder.php | https://github.com/algolia/scout-extended/blob/master/src/Builder.php | MIT |
public function __construct(?array $tags = null)
{
if ($tags !== null) {
$this->tags = $tags;
}
} | Creates a new instance of the class.
@param array|null $tags
@return void | __construct | php | algolia/scout-extended | src/Splitters/HtmlSplitter.php | https://github.com/algolia/scout-extended/blob/master/src/Splitters/HtmlSplitter.php | MIT |
protected function handleDeprecatedDeleteBy(SearchClient $client)
{
$index = $client->initIndex($this->searchables->first()->searchableAs());
$result = $index->deleteBy([
'tagFilters' => [
$this->searchables->map(function ($searchable) {
return ObjectIdEncrypter::encrypt($searchable);
})->toArray(),
],
]);
if (config('scout.synchronous', false)) {
$result->wait();
}
} | Handle deleting objects using the deprecated `deleteBy` method.
@param \Algolia\AlgoliaSearch\SearchClient $client
@return void | handleDeprecatedDeleteBy | php | algolia/scout-extended | src/Jobs/DeleteJob.php | https://github.com/algolia/scout-extended/blob/master/src/Jobs/DeleteJob.php | MIT |
public function __construct(Repository $cache, SearchClient $client)
{
$this->cache = $cache;
$this->client = $client;
} | ApiKeysRepository constructor.
@param \Illuminate\Contracts\Cache\Repository $cache
@param \Algolia\AlgoliaSearch\SearchClient $client
@return void | __construct | php | algolia/scout-extended | src/Repositories/ApiKeysRepository.php | https://github.com/algolia/scout-extended/blob/master/src/Repositories/ApiKeysRepository.php | MIT |
public function __construct(RemoteSettingsRepository $remoteRepository)
{
$this->remoteRepository = $remoteRepository;
} | UserDataRepository constructor.
@param \Algolia\ScoutExtended\Repositories\RemoteSettingsRepository $remoteRepository | __construct | php | algolia/scout-extended | src/Repositories/UserDataRepository.php | https://github.com/algolia/scout-extended/blob/master/src/Repositories/UserDataRepository.php | MIT |
public function __sleep()
{
$this->aggregator = get_class($this->first());
$this->items = $this->getSerializedPropertyValue(EloquentCollection::make($this->map(function ($aggregator) {
return $aggregator->getModel();
})));
return ['aggregator', 'items'];
} | Prepare the instance for serialization.
@return string[] | __sleep | php | algolia/scout-extended | src/Searchable/AggregatorCollection.php | https://github.com/algolia/scout-extended/blob/master/src/Searchable/AggregatorCollection.php | MIT |
public function __wakeup()
{
$this->items = $this->getRestoredPropertyValue($this->items)->map(function ($model) {
return $this->aggregator::create($model);
})->toArray();
} | Restore the model after serialization.
@return void | __wakeup | php | algolia/scout-extended | src/Searchable/AggregatorCollection.php | https://github.com/algolia/scout-extended/blob/master/src/Searchable/AggregatorCollection.php | MIT |
public function getSubscribedEvents()
{
return [
'prePersist',
'onFlush',
'loadClassMetadata',
];
} | Specifies the list of events to listen on.
@return string[] | getSubscribedEvents | php | doctrine-extensions/DoctrineExtensions | src/AbstractTrackingListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/AbstractTrackingListener.php | MIT |
public function loadClassMetadata(EventArgs $eventArgs)
{
$this->loadMetadataForObjectClass($eventArgs->getObjectManager(), $eventArgs->getClassMetadata());
} | Maps additional metadata for the object.
@param LoadClassMetadataEventArgs $eventArgs
@phpstan-param LoadClassMetadataEventArgs<ClassMetadata<object>, ObjectManager> $eventArgs
@return void | loadClassMetadata | php | doctrine-extensions/DoctrineExtensions | src/AbstractTrackingListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/AbstractTrackingListener.php | MIT |
public function prePersist(EventArgs $args)
{
$ea = $this->getEventAdapter($args);
$om = $ea->getObjectManager();
$object = $ea->getObject();
$meta = $om->getClassMetadata(get_class($object));
if ($config = $this->getConfiguration($om, $meta->getName())) {
if (isset($config['update'])) {
foreach ($config['update'] as $field) {
if (null === $meta->getReflectionProperty($field)->getValue($object)) { // let manual values
$this->updateField($object, $ea, $meta, $field);
}
}
}
if (isset($config['create'])) {
foreach ($config['create'] as $field) {
if (null === $meta->getReflectionProperty($field)->getValue($object)) { // let manual values
$this->updateField($object, $ea, $meta, $field);
}
}
}
}
} | Processes updates when an object is persisted in the manager.
@param LifecycleEventArgs $args
@phpstan-param LifecycleEventArgs<ObjectManager> $args
@return void | prePersist | php | doctrine-extensions/DoctrineExtensions | src/AbstractTrackingListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/AbstractTrackingListener.php | MIT |
public function getSubscribedEvents()
{
return [
'postLoad',
'postPersist',
'preFlush',
'onFlush',
'loadClassMetadata',
];
} | Specifies the list of events to listen
@return string[] | getSubscribedEvents | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setSkipOnLoad($bool)
{
$this->skipOnLoad = (bool) $bool;
return $this;
} | Set to skip or not onLoad event
@param bool $bool
@return static | setSkipOnLoad | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setPersistDefaultLocaleTranslation($bool)
{
$this->persistDefaultLocaleTranslation = (bool) $bool;
return $this;
} | Whether or not, to persist default locale
translation or keep it in original record
@param bool $bool
@return static | setPersistDefaultLocaleTranslation | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function getPersistDefaultLocaleTranslation()
{
return (bool) $this->persistDefaultLocaleTranslation;
} | Check if should persist default locale
translation or keep it in original record
@return bool | getPersistDefaultLocaleTranslation | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function addPendingTranslationInsert($oid, $translation)
{
$this->pendingTranslationInserts[$oid][] = $translation;
} | Add additional $translation for pending $oid object
which is being inserted
@param int $oid
@param object $translation
@return void | addPendingTranslationInsert | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function getTranslationClass(TranslatableAdapter $ea, $class)
{
return self::$configurations[$this->name][$class]['translationClass'] ?? $ea->getDefaultTranslationClass()
;
} | Get the translation class to be used
for the object $class
@param string $class
@phpstan-param class-string $class
@return string
@phpstan-return class-string | getTranslationClass | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setTranslationFallback($bool)
{
$this->translationFallback = (bool) $bool;
return $this;
} | Enable or disable translation fallback
to original record value
@param bool $bool
@return static | setTranslationFallback | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function getTranslationFallback()
{
return $this->translationFallback;
} | Weather or not is using the translation
fallback to original record
@return bool | getTranslationFallback | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setTranslatableLocale($locale)
{
$this->validateLocale($locale);
$this->locale = $locale;
return $this;
} | Set the locale to use for translation listener
@param string $locale
@return static | setTranslatableLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setDefaultLocale($locale)
{
$this->validateLocale($locale);
$this->defaultLocale = $locale;
return $this;
} | Sets the default locale, this changes behavior
to not update the original record field if locale
which is used for updating is not default
@param string $locale
@return static | setDefaultLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function getListenerLocale()
{
return $this->locale;
} | Get currently set global locale, used
extensively during query execution
@return string | getListenerLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function postLoad(EventArgs $args)
{
$ea = $this->getEventAdapter($args);
$om = $ea->getObjectManager();
$object = $ea->getObject();
$meta = $om->getClassMetadata(get_class($object));
$config = $this->getConfiguration($om, $meta->getName());
$locale = $this->defaultLocale;
$oid = null;
if (isset($config['fields'])) {
$locale = $this->getTranslatableLocale($object, $meta, $om);
$oid = spl_object_id($object);
$this->translatedInLocale[$oid] = $locale;
}
if ($this->skipOnLoad) {
return;
}
if (isset($config['fields']) && ($locale !== $this->defaultLocale || $this->persistDefaultLocaleTranslation)) {
// fetch translations
$translationClass = $this->getTranslationClass($ea, $config['useObjectClass']);
$result = $ea->loadTranslations(
$object,
$translationClass,
$locale,
$config['useObjectClass']
);
// translate object's translatable properties
foreach ($config['fields'] as $field) {
$translated = $this->defaultTranslationValue;
foreach ($result as $entry) {
if ($entry['field'] == $field) {
$translated = $entry['content'] ?? null;
break;
}
}
// update translation
if ($this->defaultTranslationValue !== $translated
|| (!$this->translationFallback && (!isset($config['fallback'][$field]) || !$config['fallback'][$field]))
|| ($this->translationFallback && isset($config['fallback'][$field]) && !$config['fallback'][$field])
) {
$ea->setTranslationValue($object, $field, $translated);
// ensure clean changeset
$ea->setOriginalObjectProperty(
$om->getUnitOfWork(),
$object,
$field,
$meta->getReflectionProperty($field)->getValue($object)
);
}
}
}
} | After object is loaded, listener updates the translations
by currently used locale
@param ManagerEventArgs $args
@phpstan-param ManagerEventArgs<ObjectManager> $args
@return void | postLoad | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function setTranslationInDefaultLocale($oid, $field, $trans)
{
if (!isset($this->translationInDefaultLocale[$oid])) {
$this->translationInDefaultLocale[$oid] = [];
}
$this->translationInDefaultLocale[$oid][$field] = $trans;
} | Sets translation object which represents translation in default language.
@param int $oid hash of basic entity
@param string $field field of basic entity
@param object|Translatable $trans Translation object
@return void | setTranslationInDefaultLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function hasTranslationsInDefaultLocale($oid)
{
return array_key_exists($oid, $this->translationInDefaultLocale);
} | Check if object has any translation object which represents translation in default language.
This is for internal use only.
@param int $oid hash of the basic entity
@return bool | hasTranslationsInDefaultLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
private function getTranslationInDefaultLocale(int $oid, string $field)
{
return $this->translationInDefaultLocale[$oid][$field] ?? null;
} | Gets translation object which represents translation in default language.
This is for internal use only.
@param int $oid hash of the basic entity
@param string $field field of basic entity
@return object|Translatable|null Returns translation object if it exists or NULL otherwise | getTranslationInDefaultLocale | php | doctrine-extensions/DoctrineExtensions | src/Translatable/TranslatableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/TranslatableListener.php | MIT |
public function translate($entity, $field, $locale, $value)
{
$meta = $this->getEntityManager()->getClassMetadata(get_class($entity));
$listener = $this->getTranslatableListener();
$config = $listener->getConfiguration($this->getEntityManager(), $meta->getName());
if (!isset($config['fields']) || !in_array($field, $config['fields'], true)) {
throw new InvalidArgumentException("Entity: {$meta->getName()} does not translate field - {$field}");
}
$needsPersist = true;
if ($locale === $listener->getTranslatableLocale($entity, $meta, $this->getEntityManager())) {
$meta->getReflectionProperty($field)->setValue($entity, $value);
$this->getEntityManager()->persist($entity);
} else {
if (isset($config['translationClass'])) {
$class = $config['translationClass'];
} else {
$ea = new TranslatableAdapterORM();
$class = $listener->getTranslationClass($ea, $config['useObjectClass']);
}
$foreignKey = $meta->getReflectionProperty($meta->getSingleIdentifierFieldName())->getValue($entity);
$objectClass = $config['useObjectClass'];
$transMeta = $this->getEntityManager()->getClassMetadata($class);
$trans = $this->findOneBy([
'locale' => $locale,
'objectClass' => $objectClass,
'field' => $field,
'foreignKey' => $foreignKey,
]);
if (!$trans) {
$trans = $transMeta->newInstance();
$transMeta->getReflectionProperty('foreignKey')->setValue($trans, $foreignKey);
$transMeta->getReflectionProperty('objectClass')->setValue($trans, $objectClass);
$transMeta->getReflectionProperty('field')->setValue($trans, $field);
$transMeta->getReflectionProperty('locale')->setValue($trans, $locale);
}
if ($listener->getDefaultLocale() != $listener->getTranslatableLocale($entity, $meta, $this->getEntityManager())
&& $locale === $listener->getDefaultLocale()) {
$listener->setTranslationInDefaultLocale(spl_object_id($entity), $field, $trans);
$needsPersist = $listener->getPersistDefaultLocaleTranslation();
}
$transformed = $this->getEntityManager()->getConnection()->convertToDatabaseValue($value, $meta->getTypeOfField($field));
$transMeta->getReflectionProperty('content')->setValue($trans, $transformed);
if ($needsPersist) {
if ($this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
$this->getEntityManager()->persist($trans);
} else {
$oid = spl_object_id($entity);
$listener->addPendingTranslationInsert($oid, $trans);
}
}
}
return $this;
} | Makes additional translation of $entity $field into $locale
using $value
@param object $entity
@param string $field
@param string $locale
@param mixed $value
@throws InvalidArgumentException
@return static | translate | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Entity/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Entity/Repository/TranslationRepository.php | MIT |
public function findTranslations($entity)
{
$result = [];
$wrapped = new EntityWrapper($entity, $this->getEntityManager());
if ($wrapped->hasValidIdentifier()) {
$entityId = $wrapped->getIdentifier();
$config = $this
->getTranslatableListener()
->getConfiguration($this->getEntityManager(), $wrapped->getMetadata()->getName());
if (!$config) {
return $result;
}
$entityClass = $config['useObjectClass'];
$translationMeta = $this->getClassMetadata(); // table inheritance support
$translationClass = $config['translationClass'] ?? $translationMeta->rootEntityName;
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('trans.content, trans.field, trans.locale')
->from($translationClass, 'trans')
->where('trans.foreignKey = :entityId', 'trans.objectClass = :entityClass')
->orderBy('trans.locale')
->setParameter('entityId', $entityId)
->setParameter('entityClass', $entityClass);
foreach ($qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
} | Loads all translations with all translatable
fields from the given entity
@param object $entity Must implement Translatable
@return array<string, array<string, string>> list of translations in locale groups | findTranslations | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Entity/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Entity/Repository/TranslationRepository.php | MIT |
public function findObjectByTranslatedField($field, $value, $class)
{
$entity = null;
$meta = $this->getEntityManager()->getClassMetadata($class);
$translationMeta = $this->getClassMetadata(); // table inheritance support
if ($meta->hasField($field)) {
$dql = "SELECT trans.foreignKey FROM {$translationMeta->rootEntityName} trans";
$dql .= ' WHERE trans.objectClass = :class';
$dql .= ' AND trans.field = :field';
$dql .= ' AND trans.content = :value';
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters([
'class' => $class,
'field' => $field,
'value' => $value,
]);
$q->setMaxResults(1);
$id = $q->getSingleScalarResult();
if (null !== $id) {
$entity = $this->getEntityManager()->find($class, $id);
}
}
return $entity;
} | Find the entity $class by the translated field.
Result is the first occurrence of translated field.
Query can be slow, since there are no indexes on such
columns
@param string $field
@param string $value
@param string $class
@phpstan-param class-string $class
@return object instance of $class or null if not found | findObjectByTranslatedField | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Entity/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Entity/Repository/TranslationRepository.php | MIT |
public function findTranslationsByObjectId($id)
{
$result = [];
if ($id) {
$translationMeta = $this->getClassMetadata(); // table inheritance support
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('trans.content, trans.field, trans.locale')
->from($translationMeta->rootEntityName, 'trans')
->where('trans.foreignKey = :entityId')
->orderBy('trans.locale')
->setParameter('entityId', $id);
$q = $qb->getQuery();
foreach ($q->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
} | Loads all translations with all translatable
fields by a given entity primary key
@param mixed $id primary key value of an entity
@return array<string, array<string, string>> | findTranslationsByObjectId | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Entity/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Entity/Repository/TranslationRepository.php | MIT |
protected function getTranslatableListener()
{
foreach ($this->getEntityManager()->getEventManager()->getAllListeners() as $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof TranslatableListener) {
return $listener;
}
}
}
throw new RuntimeException('The translation listener could not be found');
} | Get the currently used TranslatableListener
@throws RuntimeException if listener is not found
@return TranslatableListener | getTranslatableListener | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Hydrator/ORM/SimpleObjectHydrator.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Hydrator/ORM/SimpleObjectHydrator.php | MIT |
private function foreignKey($key, string $className)
{
$em = $this->getObjectManager();
$meta = $em->getClassMetadata($className);
$type = Type::getType($meta->getTypeOfField('foreignKey'));
switch (Type::lookupName($type)) {
case Types::BIGINT:
case Types::INTEGER:
case Types::SMALLINT:
return (int) $key;
default:
return (string) $key;
}
} | Transforms foreign key of translation to appropriate PHP value
to prevent database level cast
@param mixed $key foreign key value
@param string $className translation class name
@phpstan-param class-string $className translation class name
@return int|string transformed foreign key | foreignKey | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Mapping/Event/Adapter/ORM.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Mapping/Event/Adapter/ORM.php | MIT |
public function translate($document, $field, $locale, $value)
{
$meta = $this->dm->getClassMetadata(get_class($document));
$listener = $this->getTranslatableListener();
$config = $listener->getConfiguration($this->dm, $meta->getName());
if (!isset($config['fields']) || !in_array($field, $config['fields'], true)) {
throw new InvalidArgumentException("Document: {$meta->getName()} does not translate field - {$field}");
}
$modRecordValue = (!$listener->getPersistDefaultLocaleTranslation() && $locale === $listener->getDefaultLocale())
|| $listener->getTranslatableLocale($document, $meta, $this->getDocumentManager()) === $locale
;
if ($modRecordValue) {
$meta->getReflectionProperty($field)->setValue($document, $value);
$this->dm->persist($document);
} else {
if (isset($config['translationClass'])) {
$class = $config['translationClass'];
} else {
$ea = new TranslatableAdapterODM();
$class = $listener->getTranslationClass($ea, $config['useObjectClass']);
}
$foreignKey = $meta->getReflectionProperty($meta->getIdentifier()[0])->getValue($document);
$objectClass = $config['useObjectClass'];
$transMeta = $this->dm->getClassMetadata($class);
$trans = $this->findOneBy([
'locale' => $locale,
'field' => $field,
'objectClass' => $objectClass,
'foreignKey' => $foreignKey,
]);
if (!$trans) {
$trans = $transMeta->newInstance();
$transMeta->getReflectionProperty('foreignKey')->setValue($trans, $foreignKey);
$transMeta->getReflectionProperty('objectClass')->setValue($trans, $objectClass);
$transMeta->getReflectionProperty('field')->setValue($trans, $field);
$transMeta->getReflectionProperty('locale')->setValue($trans, $locale);
}
$mapping = $meta->getFieldMapping($field);
$type = $this->getType($mapping['type']);
$transformed = $type->convertToDatabaseValue($value);
$transMeta->getReflectionProperty('content')->setValue($trans, $transformed);
if ($this->dm->getUnitOfWork()->isInIdentityMap($document)) {
$this->dm->persist($trans);
} else {
$oid = spl_object_id($document);
$listener->addPendingTranslationInsert($oid, $trans);
}
}
return $this;
} | Makes additional translation of $document $field into $locale
using $value
@param object $document
@param string $field
@param string $locale
@param mixed $value
@return static | translate | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Document/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Document/Repository/TranslationRepository.php | MIT |
public function findTranslations($document)
{
$result = [];
$wrapped = new MongoDocumentWrapper($document, $this->dm);
if ($wrapped->hasValidIdentifier()) {
$documentId = $wrapped->getIdentifier();
$translationMeta = $this->getClassMetadata(); // table inheritance support
$config = $this
->getTranslatableListener()
->getConfiguration($this->dm, $wrapped->getMetadata()->getName());
if (!$config) {
return $result;
}
$documentClass = $config['useObjectClass'];
$translationClass = $config['translationClass'] ?? $translationMeta->rootDocumentName;
$qb = $this->dm->createQueryBuilder($translationClass);
$q = $qb->field('foreignKey')->equals($documentId)
->field('objectClass')->equals($documentClass)
->field('content')->exists(true)->notEqual(null)
->sort('locale', 'asc')
->getQuery();
$q->setHydrate(false);
foreach ($q->getIterator() as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
} | Loads all translations with all translatable
fields from the given entity
@param object $document
@return array<string, array<string, string>> list of translations in locale groups | findTranslations | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Document/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Document/Repository/TranslationRepository.php | MIT |
public function findObjectByTranslatedField($field, $value, $class)
{
$meta = $this->dm->getClassMetadata($class);
if (!$meta->hasField($field)) {
return null;
}
$qb = $this->createQueryBuilder();
$q = $qb->field('field')->equals($field)
->field('objectClass')->equals($meta->rootDocumentName)
->field('content')->equals($value)
->getQuery();
$q->setHydrate(false);
$result = $q->getSingleResult();
$id = $result['foreign_key'] ?? null;
if (null === $id) {
return null;
}
return $this->dm->find($class, $id);
} | Find the object $class by the translated field.
Result is the first occurrence of translated field.
Query can be slow, since there are no indexes on such
columns
@param string $field
@param string $value
@param string $class
@phpstan-param class-string $class
@return object|null instance of $class or null if not found | findObjectByTranslatedField | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Document/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Document/Repository/TranslationRepository.php | MIT |
public function findTranslationsByObjectId($id)
{
$result = [];
if ($id) {
$qb = $this->createQueryBuilder();
$q = $qb->field('foreignKey')->equals($id)
->field('content')->exists(true)->notEqual(null)
->sort('locale', 'asc')
->getQuery();
$q->setHydrate(false);
foreach ($q->getIterator() as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
} | Loads all translations with all translatable
fields by a given document primary key
@param mixed $id primary key value of document
@return array<string, array<string, string>> | findTranslationsByObjectId | php | doctrine-extensions/DoctrineExtensions | src/Translatable/Document/Repository/TranslationRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translatable/Document/Repository/TranslationRepository.php | MIT |
public function __construct($translatable, $locale, array $properties, $class, Collection $coll)
{
$this->translatable = $translatable;
$this->locale = $locale;
$this->properties = $properties;
$this->class = $class;
$this->coll = $coll;
if (!is_subclass_of($class, TranslationInterface::class)) {
throw new \InvalidArgumentException(sprintf('Translation class should implement %s, "%s" given', TranslationInterface::class, $class));
}
} | Initializes translations collection
@param object $translatable object to translate
@param string $locale translation name
@param string[] $properties object properties to translate
@param string $class translation entity|document class
@throws \InvalidArgumentException Translation class doesn't implement TranslationInterface
@phpstan-param class-string<TranslationInterface> $class
@phpstan-param Collection<int, TranslationInterface> $coll | __construct | php | doctrine-extensions/DoctrineExtensions | src/Translator/TranslationProxy.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translator/TranslationProxy.php | MIT |
public function getProxyLocale()
{
return $this->locale;
} | Returns locale name for the current translation proxy instance.
@return string | getProxyLocale | php | doctrine-extensions/DoctrineExtensions | src/Translator/TranslationProxy.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translator/TranslationProxy.php | MIT |
public function getTranslatedValue($property)
{
return $this
->findOrCreateTranslationForProperty($property, $this->getProxyLocale())
->getValue();
} | Returns translated value for specific property.
@param string $property property name
@return mixed | getTranslatedValue | php | doctrine-extensions/DoctrineExtensions | src/Translator/TranslationProxy.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translator/TranslationProxy.php | MIT |
public function setTranslatedValue($property, $value)
{
$this
->findOrCreateTranslationForProperty($property, $this->getProxyLocale())
->setValue($value);
} | Sets translated value for specific property.
@param string $property property name
@param string $value value
@return void | setTranslatedValue | php | doctrine-extensions/DoctrineExtensions | src/Translator/TranslationProxy.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Translator/TranslationProxy.php | MIT |
private function getRawDateValue($mapping)
{
$datetime = $this->clock instanceof ClockInterface ? $this->clock->now() : new \DateTimeImmutable();
$type = $mapping instanceof FieldMapping ? $mapping->type : ($mapping['type'] ?? '');
if ('integer' === $type) {
return (int) $datetime->format('U');
}
if (in_array($type, ['date_immutable', 'time_immutable', 'datetime_immutable', 'datetimetz_immutable'], true)) {
return $datetime;
}
return \DateTime::createFromImmutable($datetime);
} | Generates current timestamp for the specified mapping
@param array<string, mixed>|FieldMapping $mapping
@return \DateTimeInterface|int | getRawDateValue | php | doctrine-extensions/DoctrineExtensions | src/Timestampable/Mapping/Event/Adapter/ORM.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Timestampable/Mapping/Event/Adapter/ORM.php | MIT |
protected function isValidField($meta, $field)
{
$mapping = $meta->getFieldMapping($field);
return $mapping && in_array($mapping->type ?? $mapping['type'], self::VALID_TYPES, true);
} | Checks if $field type is valid
@param ClassMetadata<object> $meta
@param string $field
@return bool | isValidField | php | doctrine-extensions/DoctrineExtensions | src/Timestampable/Mapping/Driver/Xml.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Timestampable/Mapping/Driver/Xml.php | MIT |
protected function prePersistLogEntry($logEntry, $object)
{
} | Handle any custom LogEntry functionality that needs to be performed
before persisting it
@param LogEntryInterface $logEntry The LogEntry being persisted
@param object $object The object being Logged
@return void
@phpstan-param LogEntryInterface<T> $logEntry
@phpstan-param T $object | prePersistLogEntry | php | doctrine-extensions/DoctrineExtensions | src/Loggable/LoggableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/LoggableListener.php | MIT |
protected function getObjectChangeSetData($ea, $object, $logEntry)
{
$om = $ea->getObjectManager();
$wrapped = AbstractWrapper::wrap($object, $om);
$meta = $wrapped->getMetadata();
$config = $this->getConfiguration($om, $meta->getName());
$uow = $om->getUnitOfWork();
$newValues = [];
foreach ($ea->getObjectChangeSet($uow, $object) as $field => $changes) {
if (empty($config['versioned']) || !in_array($field, $config['versioned'], true)) {
continue;
}
$value = $changes[1];
if ($meta->isSingleValuedAssociation($field) && $value) {
if ($wrapped->isEmbeddedAssociation($field)) {
$value = $this->getObjectChangeSetData($ea, $value, $logEntry);
} else {
$oid = spl_object_id($value);
$wrappedAssoc = AbstractWrapper::wrap($value, $om);
$value = $wrappedAssoc->getIdentifier(false);
if (!is_array($value) && !$value) {
$this->pendingRelatedObjects[$oid][] = [
'log' => $logEntry,
'field' => $field,
];
}
}
}
$newValues[$field] = $value;
}
return $newValues;
} | Returns an objects changeset data
@param LoggableAdapter $ea
@param object $object
@param LogEntryInterface $logEntry
@return array<string, mixed>
@phpstan-param T $object
@phpstan-param LogEntryInterface<T> $logEntry | getObjectChangeSetData | php | doctrine-extensions/DoctrineExtensions | src/Loggable/LoggableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/LoggableListener.php | MIT |
public function getLogEntries($entity)
{
return $this->getLogEntriesQuery($entity)->getResult();
} | Loads all log entries for the given entity
@param T $entity
@return array<array-key, AbstractLogEntry<T>> | getLogEntries | php | doctrine-extensions/DoctrineExtensions | src/Loggable/Entity/Repository/LogEntryRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/Entity/Repository/LogEntryRepository.php | MIT |
public function getLogEntriesQuery($entity)
{
$wrapped = new EntityWrapper($entity, $this->getEntityManager());
$objectClass = $wrapped->getMetadata()->getName();
$meta = $this->getClassMetadata();
$dql = "SELECT log FROM {$meta->getName()} log";
$dql .= ' WHERE log.objectId = :objectId';
$dql .= ' AND log.objectClass = :objectClass';
$dql .= ' ORDER BY log.version DESC';
$objectId = (string) $wrapped->getIdentifier(false, true);
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters([
'objectId' => $objectId,
'objectClass' => $objectClass,
]);
return $q;
} | Get the query for loading of log entries
@param T $entity
@return Query | getLogEntriesQuery | php | doctrine-extensions/DoctrineExtensions | src/Loggable/Entity/Repository/LogEntryRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/Entity/Repository/LogEntryRepository.php | MIT |
public function revert($entity, $version = 1)
{
$wrapped = new EntityWrapper($entity, $this->getEntityManager());
$objectMeta = $wrapped->getMetadata();
$objectClass = $objectMeta->getName();
$meta = $this->getClassMetadata();
$dql = "SELECT log FROM {$meta->getName()} log";
$dql .= ' WHERE log.objectId = :objectId';
$dql .= ' AND log.objectClass = :objectClass';
$dql .= ' AND log.version <= :version';
$dql .= ' ORDER BY log.version DESC';
$objectId = (string) $wrapped->getIdentifier(false, true);
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters([
'objectId' => $objectId,
'objectClass' => $objectClass,
'version' => $version,
]);
$config = $this->getLoggableListener()->getConfiguration($this->getEntityManager(), $objectMeta->getName());
$fields = $config['versioned'];
$filled = false;
$logsFound = false;
$logs = $q->toIterable();
assert($logs instanceof \Generator);
while ((null !== $log = $logs->current()) && !$filled) {
$logsFound = true;
$logs->next();
if ($data = $log->getData()) {
foreach ($data as $field => $value) {
if (in_array($field, $fields, true)) {
$this->mapValue($objectMeta, $field, $value);
$wrapped->setPropertyValue($field, $value);
unset($fields[array_search($field, $fields, true)]);
}
}
}
$filled = [] === $fields;
}
if (!$logsFound) {
throw new UnexpectedValueException('Could not find any log entries under version: '.$version);
}
/*if (count($fields)) {
throw new \Gedmo\Exception\UnexpectedValueException('Could not fully revert the entity to version: '.$version);
}*/
} | Reverts given $entity to $revision by
restoring all fields from that $revision.
After this operation you will need to
persist and flush the $entity.
@param T $entity
@param int $version
@throws UnexpectedValueException
@return void | revert | php | doctrine-extensions/DoctrineExtensions | src/Loggable/Entity/Repository/LogEntryRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/Entity/Repository/LogEntryRepository.php | MIT |
public function getLogEntries($document)
{
$wrapped = new MongoDocumentWrapper($document, $this->dm);
$objectId = $wrapped->getIdentifier();
$qb = $this->createQueryBuilder();
$qb->field('objectId')->equals($objectId);
$qb->field('objectClass')->equals($wrapped->getMetadata()->getName());
$qb->sort('version', 'DESC');
return $qb->getQuery()->getIterator()->toArray();
} | Loads all log entries for the
given $document
@param object $document
@return LogEntry[]
@phpstan-param T $document
@phpstan-return array<array-key, LogEntry<T>> | getLogEntries | php | doctrine-extensions/DoctrineExtensions | src/Loggable/Document/Repository/LogEntryRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/Document/Repository/LogEntryRepository.php | MIT |
public function revert($document, $version = 1)
{
$wrapped = new MongoDocumentWrapper($document, $this->dm);
$objectMeta = $wrapped->getMetadata();
$objectId = $wrapped->getIdentifier();
$qb = $this->createQueryBuilder();
$qb->field('objectId')->equals($objectId);
$qb->field('objectClass')->equals($objectMeta->getName());
$qb->field('version')->lte((int) $version);
$qb->sort('version', 'ASC');
$logs = $qb->getQuery()->getIterator()->toArray();
if ([] === $logs) {
throw new UnexpectedValueException('Count not find any log entries under version: '.$version);
}
$data = [[]];
while ($log = array_shift($logs)) {
$data[] = $log->getData();
}
$data = array_merge(...$data);
$this->fillDocument($document, $data);
} | Reverts given $document to $revision by
restoring all fields from that $revision.
After this operation you will need to
persist and flush the $document.
@param object $document
@param int $version
@throws UnexpectedValueException
@return void
@phpstan-param T $document | revert | php | doctrine-extensions/DoctrineExtensions | src/Loggable/Document/Repository/LogEntryRepository.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Loggable/Document/Repository/LogEntryRepository.php | MIT |
public function setDeletedAt(?\DateTime $deletedAt = null)
{
$this->deletedAt = $deletedAt;
return $this;
} | Set or clear the deleted at timestamp.
@return self | setDeletedAt | php | doctrine-extensions/DoctrineExtensions | src/SoftDeleteable/Traits/SoftDeleteable.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/SoftDeleteable/Traits/SoftDeleteable.php | MIT |
public function getDeletedAt()
{
return $this->deletedAt;
} | Get the deleted at timestamp value. Will return null if
the entity has not been soft deleted.
@return \DateTime|null | getDeletedAt | php | doctrine-extensions/DoctrineExtensions | src/SoftDeleteable/Traits/SoftDeleteable.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/SoftDeleteable/Traits/SoftDeleteable.php | MIT |
public function isDeleted()
{
return null !== $this->deletedAt;
} | Check if the entity has been soft deleted.
@return bool | isDeleted | php | doctrine-extensions/DoctrineExtensions | src/SoftDeleteable/Traits/SoftDeleteable.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/SoftDeleteable/Traits/SoftDeleteable.php | MIT |
public function getIntegrityActions()
{
return self::INTEGRITY_ACTIONS;
} | Returns a list of available integrity actions
@return string[]
@phpstan-return array<int, self::NULLIFY|self::PULL|self::RESTRICT> | getIntegrityActions | php | doctrine-extensions/DoctrineExtensions | src/ReferenceIntegrity/Mapping/Validator.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/ReferenceIntegrity/Mapping/Validator.php | MIT |
public function getConfiguration(ObjectManager $objectManager, $class)
{
if (isset(self::$configurations[$this->name][$class])) {
return self::$configurations[$this->name][$class];
}
$config = [];
$cacheItemPool = $this->getCacheItemPool($objectManager);
$cacheId = ExtensionMetadataFactory::getCacheId($class, $this->getNamespace());
$cacheItem = $cacheItemPool->getItem($cacheId);
if ($cacheItem->isHit()) {
$config = $cacheItem->get();
self::$configurations[$this->name][$class] = $config;
} else {
// re-generate metadata on cache miss
$this->loadMetadataForObjectClass($objectManager, $objectManager->getClassMetadata($class));
if (isset(self::$configurations[$this->name][$class])) {
$config = self::$configurations[$this->name][$class];
}
}
$objectClass = $config['useObjectClass'] ?? $class;
if ($objectClass !== $class) {
$this->getConfiguration($objectManager, $objectClass);
}
return $config;
} | Get the configuration for specific object class
if cache driver is present it scans it also
@param string $class
@phpstan-param class-string $class
@return array<string, mixed>
@phpstan-return TConfig | getConfiguration | php | doctrine-extensions/DoctrineExtensions | src/Mapping/MappedEventSubscriber.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/MappedEventSubscriber.php | MIT |
public function getExtensionMetadataFactory(ObjectManager $objectManager)
{
$oid = spl_object_id($objectManager);
if (!isset($this->extensionMetadataFactory[$oid])) {
if (false === $this->annotationReader) {
// create default annotation/attribute reader for extensions
$this->annotationReader = $this->getDefaultAnnotationReader();
}
$this->extensionMetadataFactory[$oid] = new ExtensionMetadataFactory(
$objectManager,
$this->getNamespace(),
$this->annotationReader,
$this->getCacheItemPool($objectManager)
);
}
return $this->extensionMetadataFactory[$oid];
} | Get extended metadata mapping reader
@return ExtensionMetadataFactory | getExtensionMetadataFactory | php | doctrine-extensions/DoctrineExtensions | src/Mapping/MappedEventSubscriber.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/MappedEventSubscriber.php | MIT |
public function loadMetadataForObjectClass(ObjectManager $objectManager, $metadata)
{
assert($metadata instanceof DocumentClassMetadata || $metadata instanceof EntityClassMetadata || $metadata instanceof LegacyEntityClassMetadata);
$factory = $this->getExtensionMetadataFactory($objectManager);
try {
$config = $factory->getExtensionMetadata($metadata);
} catch (\ReflectionException $e) {
// entity\document generator is running
$config = []; // will not store a cached version, to remap later
}
if ([] !== $config) {
self::$configurations[$this->name][$metadata->getName()] = $config;
}
} | Scans the objects for extended annotations
event subscribers must subscribe to loadClassMetadata event
@param ClassMetadata<object> $metadata
@return void | loadMetadataForObjectClass | php | doctrine-extensions/DoctrineExtensions | src/Mapping/MappedEventSubscriber.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/MappedEventSubscriber.php | MIT |
protected function getEventAdapter(EventArgs $args)
{
$class = get_class($args);
if (preg_match('@Doctrine\\\([^\\\]+)@', $class, $m) && in_array($m[1], ['ODM', 'ORM'], true)) {
if (!isset($this->adapters[$m[1]])) {
$adapterClass = $this->getNamespace().'\\Mapping\\Event\\Adapter\\'.$m[1];
if (!\class_exists($adapterClass)) {
$adapterClass = 'Gedmo\\Mapping\\Event\\Adapter\\'.$m[1];
}
$this->adapters[$m[1]] = new $adapterClass();
if ($this->adapters[$m[1]] instanceof ClockAwareAdapterInterface && $this->clock instanceof ClockInterface) {
$this->adapters[$m[1]]->setClock($this->clock);
}
}
$this->adapters[$m[1]]->setEventArgs($args);
return $this->adapters[$m[1]];
}
throw new InvalidArgumentException('Event mapper does not support event arg class: '.$class);
} | Get an event adapter to handle event specific
methods
@throws InvalidArgumentException if event is not recognized
@return AdapterInterface
@phpstan-return TEventAdapter | getEventAdapter | php | doctrine-extensions/DoctrineExtensions | src/Mapping/MappedEventSubscriber.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/MappedEventSubscriber.php | MIT |
protected function setFieldValue(AdapterInterface $adapter, $object, $field, $oldValue, $newValue)
{
$manager = $adapter->getObjectManager();
$meta = $manager->getClassMetadata(get_class($object));
$uow = $manager->getUnitOfWork();
$meta->getReflectionProperty($field)->setValue($object, $newValue);
$uow->propertyChanged($object, $field, $oldValue, $newValue);
$adapter->recomputeSingleObjectChangeSet($uow, $meta, $object);
} | Sets the value for a mapped field
@param object $object
@param string $field
@param mixed $oldValue
@param mixed $newValue
@return void | setFieldValue | php | doctrine-extensions/DoctrineExtensions | src/Mapping/MappedEventSubscriber.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/MappedEventSubscriber.php | MIT |
public function createLifecycleEventArgsInstance($document, $documentManager)
{
Deprecation::trigger(
'gedmo/doctrine-extensions',
'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2649',
'Using "%s()" method is deprecated since gedmo/doctrine-extensions 3.15 and will be removed in version 4.0.',
__METHOD__
);
return new LifecycleEventArgs($document, $documentManager);
} | @deprecated to be removed in 4.0, use custom lifecycle event classes instead.
Creates a ODM specific LifecycleEventArgs.
@param object $document
@param DocumentManager $documentManager
@return LifecycleEventArgs | createLifecycleEventArgsInstance | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Event/Adapter/ODM.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Event/Adapter/ODM.php | MIT |
public function createLifecycleEventArgsInstance($object, $entityManager)
{
Deprecation::trigger(
'gedmo/doctrine-extensions',
'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2649',
'Using "%s()" method is deprecated since gedmo/doctrine-extensions 3.15 and will be removed in version 4.0.',
__METHOD__
);
if (!class_exists(LifecycleEventArgs::class)) {
throw new \RuntimeException(sprintf('Cannot call %s() when using doctrine/orm >=3.0, use a custom lifecycle event class instead.', __METHOD__));
}
return new LifecycleEventArgs($object, $entityManager);
} | @deprecated use custom lifecycle event classes instead
Creates an ORM specific LifecycleEventArgs
@param object $object
@param EntityManagerInterface $entityManager
@return LifecycleEventArgs | createLifecycleEventArgsInstance | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Event/Adapter/ORM.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Event/Adapter/ORM.php | MIT |
protected function _getAttribute(\SimpleXMLElement $node, $attributeName)
{
$attributes = $node->attributes();
return (string) $attributes[$attributeName];
} | Get attribute value.
As we are supporting namespaces the only way to get to the attributes under a node is to use attributes function on it
@param string $attributeName
@return string | _getAttribute | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/Xml.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/Xml.php | MIT |
protected function _getBooleanAttribute(\SimpleXMLElement $node, $attributeName)
{
$rawValue = strtolower($this->_getAttribute($node, $attributeName));
if ('1' === $rawValue || 'true' === $rawValue) {
return true;
}
if ('0' === $rawValue || 'false' === $rawValue) {
return false;
}
throw new InvalidMappingException(sprintf("Attribute %s must have a valid boolean value, '%s' found", $attributeName, $this->_getAttribute($node, $attributeName)));
} | Get boolean attribute value.
As we are supporting namespaces the only way to get to the attributes under a node is to use attributes function on it
@param string $attributeName
@return bool | _getBooleanAttribute | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/Xml.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/Xml.php | MIT |
protected function _isAttributeSet(\SimpleXMLElement $node, $attributeName)
{
$attributes = $node->attributes();
return isset($attributes[$attributeName]);
} | does attribute exist under a specific node
As we are supporting namespaces the only way to get to the attributes under a node is to use attributes function on it
@param string $attributeName
@return bool | _isAttributeSet | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/Xml.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/Xml.php | MIT |
public function setOriginalDriver($driver)
{
$this->_originalDriver = $driver;
} | Passes in the mapping read by original driver
@param MappingDriver $driver
@return void | setOriginalDriver | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/File.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/File.php | MIT |
protected function _getMapping($className)
{
// try loading mapping from original driver first
$mapping = null;
if (null !== $this->_originalDriver) {
if ($this->_originalDriver instanceof FileDriver) {
$mapping = $this->_originalDriver->getElement($className);
}
}
// if no mapping found try to load mapping file again
if (null === $mapping) {
$yaml = $this->_loadMappingFile($this->locator->findMappingFile($className));
$mapping = $yaml[$className];
}
return $mapping;
} | Tries to get a mapping for a given class
@param string $className
@return array<string, mixed>|object|null
@phpstan-param class-string $className | _getMapping | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/File.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/File.php | MIT |
protected function getRelatedClassName($metadata, $name)
{
if (class_exists($name) || interface_exists($name)) {
return $name;
}
$refl = $metadata->getReflectionClass();
$ns = $refl->getNamespaceName();
$className = $ns.'\\'.$name;
return class_exists($className) ? $className : '';
} | Try to find out related class name out of mapping
@param ClassMetadata<object> $metadata the mapped class metadata
@param string $name the related object class name
@return string related class name or empty string if does not exist
@phpstan-param class-string|string $name
@phpstan-return class-string|'' | getRelatedClassName | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/File.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/File.php | MIT |
public function getDrivers()
{
return $this->_drivers;
} | Get the array of nested drivers.
@return array<string, Driver> | getDrivers | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/Chain.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/Chain.php | MIT |
public function setOriginalDriver($driver)
{
// not needed here
} | Passes in the mapping read by original driver | setOriginalDriver | php | doctrine-extensions/DoctrineExtensions | src/Mapping/Driver/Chain.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Mapping/Driver/Chain.php | MIT |
public function processFile(AdapterInterface $ea, $object, $action)
{
$oid = spl_object_id($object);
$om = $ea->getObjectManager();
\assert($om instanceof EntityManagerInterface);
$uow = $om->getUnitOfWork();
$meta = $om->getClassMetadata(get_class($object));
$config = $this->getConfiguration($om, $meta->getName());
if (!$config || !isset($config['uploadable']) || !$config['uploadable']) {
// Nothing to do
return;
}
$refl = $meta->getReflectionClass();
$fileInfo = $this->fileInfoObjects[$oid]['fileInfo'];
$evm = $om->getEventManager();
if ($evm->hasListeners(Events::uploadablePreFileProcess)) {
$evm->dispatchEvent(Events::uploadablePreFileProcess, new UploadablePreFileProcessEventArgs(
$this,
$om,
$config,
$fileInfo,
$object,
$action
));
}
// Validations
if ($config['maxSize'] > 0 && $fileInfo->getSize() > $config['maxSize']) {
$msg = 'File "%s" exceeds the maximum allowed size of %d bytes. File size: %d bytes';
throw new UploadableMaxSizeException(sprintf($msg, $fileInfo->getName(), $config['maxSize'], $fileInfo->getSize()));
}
$mime = $this->mimeTypeGuesser->guess($fileInfo->getTmpName());
if (null === $mime) {
throw new UploadableCouldntGuessMimeTypeException(sprintf('Couldn\'t guess mime type for file "%s".', $fileInfo->getName()));
}
if ($config['allowedTypes'] || $config['disallowedTypes']) {
$ok = $config['allowedTypes'] ? false : true;
$mimes = $config['allowedTypes'] ?: $config['disallowedTypes'];
foreach ($mimes as $m) {
if ($mime === $m) {
$ok = $config['allowedTypes'] ? true : false;
break;
}
}
if (!$ok) {
throw new UploadableInvalidMimeTypeException(sprintf('Invalid mime type "%s" for file "%s".', $mime, $fileInfo->getName()));
}
}
$path = $this->getPath($meta, $config, $object);
if (self::ACTION_UPDATE === $action) {
// First we add the original file to the pendingFileRemovals array
$this->addFileRemoval($meta, $config, $object);
}
// We generate the filename based on configuration
$generatorNamespace = 'Gedmo\Uploadable\FilenameGenerator';
switch ($config['filenameGenerator']) {
case Validator::FILENAME_GENERATOR_ALPHANUMERIC:
$generatorClass = $generatorNamespace.'\FilenameGeneratorAlphanumeric';
break;
case Validator::FILENAME_GENERATOR_SHA1:
$generatorClass = $generatorNamespace.'\FilenameGeneratorSha1';
break;
case Validator::FILENAME_GENERATOR_NONE:
$generatorClass = false;
break;
default:
$generatorClass = $config['filenameGenerator'];
}
$info = $this->moveFile($fileInfo, $path, $generatorClass, $config['allowOverwrite'], $config['appendNumber'], $object);
// We override the mime type with the guessed one
$info['fileMimeType'] = $mime;
if ('' !== $config['callback']) {
$callbackMethod = $refl->getMethod($config['callback']);
$callbackMethod->setAccessible(true);
$callbackMethod->invokeArgs($object, [$info]);
}
if ($config['filePathField']) {
$this->updateField($object, $uow, $ea, $meta, $config['filePathField'], $info['filePath']);
}
if ($config['fileNameField']) {
$this->updateField($object, $uow, $ea, $meta, $config['fileNameField'], $info['fileName']);
}
if ($config['fileMimeTypeField']) {
$this->updateField($object, $uow, $ea, $meta, $config['fileMimeTypeField'], $info['fileMimeType']);
}
if ($config['fileSizeField']) {
$value = $om->getConnection()->convertToPHPValue(
$info['fileSize'],
$meta->getTypeOfField($config['fileSizeField'])
);
$this->updateField($object, $uow, $ea, $meta, $config['fileSizeField'], $value);
}
$ea->recomputeSingleObjectChangeSet($uow, $meta, $object);
if ($evm->hasListeners(Events::uploadablePostFileProcess)) {
$evm->dispatchEvent(Events::uploadablePostFileProcess, new UploadablePostFileProcessEventArgs(
$this,
$om,
$config,
$fileInfo,
$object,
$action
));
}
unset($this->fileInfoObjects[$oid]);
} | If it's a Uploadable object, verify if the file was uploaded.
If that's the case, process it.
@param object $object
@param string $action
@throws UploadableNoPathDefinedException
@throws UploadableCouldntGuessMimeTypeException
@throws UploadableMaxSizeException
@throws UploadableInvalidMimeTypeException
@return void | processFile | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function removeFile($filePath)
{
if (is_file($filePath)) {
return @unlink($filePath);
}
return false;
} | Simple wrapper for the function "unlink" to ease testing
@param string $filePath
@return bool | removeFile | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function moveFile(FileInfoInterface $fileInfo, $path, $filenameGeneratorClass = false, $overwrite = false, $appendNumber = false, $object = null)
{
if ($fileInfo->getError() > 0) {
switch ($fileInfo->getError()) {
case 1:
$msg = 'Size of uploaded file "%s" exceeds limit imposed by directive "upload_max_filesize" in php.ini';
throw new UploadableIniSizeException(sprintf($msg, $fileInfo->getName()));
case 2:
$msg = 'Size of uploaded file "%s" exceeds limit imposed by option MAX_FILE_SIZE in your form.';
throw new UploadableFormSizeException(sprintf($msg, $fileInfo->getName()));
case 3:
$msg = 'File "%s" was partially uploaded.';
throw new UploadablePartialException(sprintf($msg, $fileInfo->getName()));
case 4:
$msg = 'No file was uploaded!';
throw new UploadableNoFileException($msg);
case 6:
$msg = 'Upload failed. Temp dir is missing.';
throw new UploadableNoTmpDirException($msg);
case 7:
$msg = 'File "%s" couldn\'t be uploaded because directory is not writable.';
throw new UploadableCantWriteException(sprintf($msg, $fileInfo->getName()));
case 8:
$msg = 'A PHP Extension stopped the uploaded for some reason.';
throw new UploadableExtensionException($msg);
default:
throw new UploadableUploadException(sprintf('There was an unknown problem while uploading file "%s"', $fileInfo->getName()));
}
}
$info = [
'fileName' => '',
'fileExtension' => '',
'fileWithoutExt' => '',
'origFileName' => '',
'filePath' => '',
'fileMimeType' => $fileInfo->getType(),
'fileSize' => $fileInfo->getSize(),
];
$info['fileName'] = basename($fileInfo->getName());
$info['filePath'] = $path.'/'.$info['fileName'];
$hasExtension = strrpos($info['fileName'], '.');
if ($hasExtension) {
$info['fileExtension'] = substr($info['filePath'], strrpos($info['filePath'], '.'));
$info['fileWithoutExt'] = substr($info['filePath'], 0, strrpos($info['filePath'], '.'));
} else {
$info['fileWithoutExt'] = $info['filePath'];
}
// Save the original filename for later use
$info['origFileName'] = $info['fileName'];
// Now we generate the filename using the configured class
if (false !== $filenameGeneratorClass) {
$filename = $filenameGeneratorClass::generate(
str_replace($path.'/', '', $info['fileWithoutExt']),
$info['fileExtension'],
$object
);
$info['filePath'] = str_replace(
'/'.$info['fileName'],
'/'.$filename,
$info['filePath']
);
$info['fileName'] = $filename;
if ($pos = strrpos($info['filePath'], '.')) {
// ignores positions like "./file" at 0 see #915
$info['fileWithoutExt'] = substr($info['filePath'], 0, $pos);
} else {
$info['fileWithoutExt'] = $info['filePath'];
}
}
if (is_file($info['filePath'])) {
if ($overwrite) {
$this->cancelFileRemoval($info['filePath']);
$this->removeFile($info['filePath']);
} elseif ($appendNumber) {
$counter = 1;
$info['filePath'] = $info['fileWithoutExt'].'-'.$counter.$info['fileExtension'];
do {
$info['filePath'] = $info['fileWithoutExt'].'-'.(++$counter).$info['fileExtension'];
} while (is_file($info['filePath']));
} else {
throw new UploadableFileAlreadyExistsException(sprintf('File "%s" already exists!', $info['filePath']));
}
} | Moves the file to the specified path
@param string $path
@param string|bool $filenameGeneratorClass
@param bool $overwrite
@param bool $appendNumber
@param object $object
@throws UploadableUploadException
@throws UploadableNoFileException
@throws UploadableExtensionException
@throws UploadableIniSizeException
@throws UploadableFormSizeException
@throws UploadableFileAlreadyExistsException
@throws UploadablePartialException
@throws UploadableNoTmpDirException
@throws UploadableCantWriteException
@return array<string, int|string|null>
@phpstan-param class-string|false $filenameGeneratorClass | moveFile | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function doMoveFile($source, $dest, $isUploadedFile = true)
{
return $isUploadedFile ? @move_uploaded_file($source, $dest) : @copy($source, $dest);
} | Simple wrapper method used to move the file. If it's an uploaded file
it will use the "move_uploaded_file method. If it's not, it will
simple move it
@param string $source Source file
@param string $dest Destination file
@param bool $isUploadedFile Whether this is an uploaded file?
@return bool | doMoveFile | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function getDefaultFileInfoClass()
{
return $this->defaultFileInfoClass;
} | Returns file info default class
@return class-string<FileInfoInterface> | getDefaultFileInfoClass | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function addEntityFileInfo($entity, $fileInfo)
{
$fileInfoClass = $this->getDefaultFileInfoClass();
$fileInfo = is_array($fileInfo) ? new $fileInfoClass($fileInfo) : $fileInfo;
if (!$fileInfo instanceof FileInfoInterface) {
$msg = 'You must pass an instance of FileInfoInterface or a valid array for entity of class "%s".';
throw new \RuntimeException(sprintf($msg, get_class($entity)));
}
$this->fileInfoObjects[spl_object_id($entity)] = [
'entity' => $entity,
'fileInfo' => $fileInfo,
];
} | Adds a FileInfoInterface object for the given entity
@param object $entity
@param array<string, mixed>|FileInfoInterface $fileInfo
@throws \RuntimeException
@return void | addEntityFileInfo | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
protected function getPropertyValueFromObject(ClassMetadata $meta, $propertyName, $object)
{
$getFilePath = \Closure::bind(fn (string $propertyName) => $this->{$propertyName}, $object, $meta->getReflectionClass()->getName());
return $getFilePath($propertyName);
} | Returns value of the entity's property
@param ClassMetadata<object> $meta
@param string $propertyName
@param object $object
@return mixed | getPropertyValueFromObject | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
protected function getFilePathFieldValue(ClassMetadata $meta, array $config, $object)
{
return $this->getPropertyValueFromObject($meta, $config['filePathField'], $object);
} | Returns the path of the entity's file
@param ClassMetadata<object> $meta
@param array<string, mixed> $config
@param object $object
@return string | getFilePathFieldValue | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
protected function getFileNameFieldValue(ClassMetadata $meta, array $config, $object)
{
return $this->getPropertyValueFromObject($meta, $config['fileNameField'], $object);
} | Returns the name of the entity's file
@param ClassMetadata<object> $meta
@param array<string, mixed> $config
@param object $object
@return string | getFileNameFieldValue | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/UploadableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/UploadableListener.php | MIT |
public function getListener()
{
return $this->uploadableListener;
} | Retrieve the associated listener
@return UploadableListener | getListener | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/Event/UploadableBaseEventArgs.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/Event/UploadableBaseEventArgs.php | MIT |
public function getEntityManager()
{
Deprecation::trigger(
'gedmo/doctrine-extensions',
'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2639',
'"%s()" is deprecated since gedmo/doctrine-extensions 3.14 and will be removed in version 4.0.',
__METHOD__
);
return $this->em;
} | Retrieve associated EntityManager
@return EntityManagerInterface | getEntityManager | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/Event/UploadableBaseEventArgs.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/Event/UploadableBaseEventArgs.php | MIT |
public function getObjectManager()
{
return $this->em;
} | Retrieve associated EntityManager
@return ObjectManager | getObjectManager | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/Event/UploadableBaseEventArgs.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/Event/UploadableBaseEventArgs.php | MIT |
public function getExtensionConfiguration()
{
return $this->extensionConfiguration;
} | Retrieve associated Uploadable extension configuration
@return array | getExtensionConfiguration | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/Event/UploadableBaseEventArgs.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/Event/UploadableBaseEventArgs.php | MIT |
public function getFileInfo()
{
return $this->fileInfo;
} | Retrieve the FileInfo associated with this entity.
@return FileInfoInterface | getFileInfo | php | doctrine-extensions/DoctrineExtensions | src/Uploadable/Event/UploadableBaseEventArgs.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Uploadable/Event/UploadableBaseEventArgs.php | MIT |
public function getFieldValue($meta, $field, $eventAdapter)
{
$actor = $this->actorProvider instanceof ActorProviderInterface ? $this->actorProvider->getActor() : $this->user;
if ($meta->hasAssociation($field)) {
if (null !== $actor && !is_object($actor)) {
throw new InvalidArgumentException('Blame is reference, user must be an object');
}
return $actor;
}
// ok so it's not an association, then it is a string, or an object
if (is_object($actor)) {
if (method_exists($actor, 'getUserIdentifier')) {
return (string) $actor->getUserIdentifier();
}
if (method_exists($actor, 'getUsername')) {
return (string) $actor->getUsername();
}
if (method_exists($actor, '__toString')) {
return $actor->__toString();
}
throw new InvalidArgumentException('Field expects string, user must be a string, or object should have method getUserIdentifier, getUsername or __toString');
}
return $actor;
} | Get the user value to set on a blameable field
@param ClassMetadata<object> $meta
@param string $field
@param BlameableAdapter $eventAdapter
@return mixed | getFieldValue | php | doctrine-extensions/DoctrineExtensions | src/Blameable/BlameableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Blameable/BlameableListener.php | MIT |
public function setUserValue($user)
{
$this->user = $user;
} | Set a user value to return.
If an actor provider is also provided, it will take precedence over this value.
@param mixed $user
@return void | setUserValue | php | doctrine-extensions/DoctrineExtensions | src/Blameable/BlameableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Blameable/BlameableListener.php | MIT |
protected function processInsert(SortableAdapter $ea, array $config, $meta, $object)
{
$old = $meta->getReflectionProperty($config['position'])->getValue($object);
$newPosition = $meta->getReflectionProperty($config['position'])->getValue($object);
if (null === $newPosition) {
$newPosition = -1;
}
// Get groups
$groups = $this->getGroups($meta, $config, $object);
// Get hash
$hash = $this->getHash($groups, $config);
// Get max position
if (!isset($this->maxPositions[$hash])) {
$this->maxPositions[$hash] = $this->getMaxPosition($ea, $meta, $config, $object);
}
// Compute position if it is negative
if ($newPosition < 0) {
$newPosition += $this->maxPositions[$hash] + 2; // position == -1 => append at end of list
if ($newPosition < 0) {
$newPosition = 0;
}
}
// Set position to max position if it is too big
$newPosition = min([$this->maxPositions[$hash] + 1, $newPosition]);
// Compute relocations
// New inserted entities should not be relocated by position update, so we exclude it.
// Otherwise they could be relocated unintentionally.
$relocation = [$hash, $config['useObjectClass'], $groups, $newPosition, -1, +1, [$object]];
// Apply existing relocations
$applyDelta = 0;
if (isset($this->relocations[$hash])) {
foreach ($this->relocations[$hash]['deltas'] as $delta) {
if ($delta['start'] <= $newPosition
&& ($delta['stop'] > $newPosition || $delta['stop'] < 0)) {
$applyDelta += $delta['delta'];
}
}
}
$newPosition += $applyDelta;
// Add relocations
call_user_func_array([$this, 'addRelocation'], $relocation);
// Set new position
if ($old < 0 || null === $old) {
$this->setFieldValue($ea, $object, $config['position'], $old, $newPosition);
}
} | Computes node positions and updates the sort field in memory and in the db
@param array<string, mixed> $config
@param ClassMetadata<object> $meta
@param object $object
@phpstan-param SortableConfiguration $config
@return void | processInsert | php | doctrine-extensions/DoctrineExtensions | src/Sortable/SortableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Sortable/SortableListener.php | MIT |
public function getFieldValue($meta, $field, $eventAdapter)
{
if ($this->ipAddressProvider instanceof IpAddressProviderInterface) {
return $this->ipAddressProvider->getAddress();
}
return $this->ip;
} | Get the IP address value to set on an IP address field
@param ClassMetadata<object> $meta
@param string $field
@param IpTraceableAdapter $eventAdapter
@return string|null | getFieldValue | php | doctrine-extensions/DoctrineExtensions | src/IpTraceable/IpTraceableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/IpTraceable/IpTraceableListener.php | MIT |
public function setIpValue($ip = null)
{
if (isset($ip) && false === filter_var($ip, FILTER_VALIDATE_IP)) {
throw new InvalidArgumentException("ip address is not valid $ip");
}
$this->ip = $ip;
} | Set an IP address value to return.
If an IP address provider is also provided, it will take precedence over this value.
@param string|null $ip
@throws InvalidArgumentException
@return void | setIpValue | php | doctrine-extensions/DoctrineExtensions | src/IpTraceable/IpTraceableListener.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/IpTraceable/IpTraceableListener.php | MIT |
protected function prepare()
{
$this->doPrepareWithCompat();
} | Executes one-time preparation tasks, once each time hydration is started
through {@link hydrateAll} or {@link toIterable()}.
@return void | prepare | php | doctrine-extensions/DoctrineExtensions | src/Tool/ORM/Hydration/HydratorCompat.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Hydration/HydratorCompat.php | MIT |
protected function cleanup()
{
$this->doCleanupWithCompat();
} | Executes one-time cleanup tasks at the end of a hydration that was initiated
through {@link hydrateAll} or {@link toIterable()}.
@return void | cleanup | php | doctrine-extensions/DoctrineExtensions | src/Tool/ORM/Hydration/HydratorCompat.php | https://github.com/doctrine-extensions/DoctrineExtensions/blob/master/src/Tool/ORM/Hydration/HydratorCompat.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.