code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
public function getIndexes(): \Generator
{
$definitions = $this->reflection->getProperty('indexes') ?? [];
foreach ($definitions as $definition) {
yield $this->castIndex($definition);
}
} | Returns set of declared indexes.
Example:
const INDEXES = [
[self::UNIQUE, 'email'],
[self::INDEX, 'status', 'balance'],
[self::INDEX, 'public_id']
];
@do generator
@return \Generator|IndexDefinition[]
@throws DefinitionException |
public function declareTable(AbstractTable $table): AbstractTable
{
return $this->renderer->renderColumns(
$this->getFields(),
$this->getDefaults(),
$table
);
} | {@inheritdoc} |
public function getRelations(): \Generator
{
$schema = $this->reflection->getSchema();
foreach ($schema as $name => $definition) {
if (!$this->isRelation($definition)) {
continue;
}
/**
* We expect relations to be defined in a follow... | {@inheritdoc} |
public function packSchema(SchemaBuilder $builder, AbstractTable $table): array
{
return [
RecordEntity::SH_PRIMARY_KEY => current($table->getPrimaryKeys()),
//Default entity values
RecordEntity::SH_DEFAULTS => $this->packDefaults($table),
//Entity behavi... | {@inheritdoc} |
protected function packDefaults(AbstractTable $table): array
{
//We need mutators to normalize default values
$mutators = $this->buildMutators($table);
$defaults = [];
foreach ($table->getColumns() as $column) {
$field = $column->getName();
$default = $colum... | Generate set of default values to be used by record.
@param AbstractTable $table
@return array |
protected function buildMutators(AbstractTable $table): array
{
$mutators = $this->reflection->getMutators();
//Trying to resolve mutators based on field type
foreach ($table->getColumns() as $column) {
//Resolved mutators
$resolved = [];
if (!empty($fil... | Generate set of mutators associated with entity fields using user defined and automatic
mutators.
@see MutatorsConfig
@param AbstractTable $table
@return array |
protected function castIndex(array $definition)
{
$name = null;
$unique = null;
$columns = [];
foreach ($definition as $key => $value) {
if ($key == RecordEntity::INDEX || $key == RecordEntity::UNIQUE) {
$unique = ($key === RecordEntity::UNIQUE);
... | @param array $definition
@return IndexDefinition
@throws DefinitionException |
protected function mutateValue(array $mutators, string $field, $default)
{
//Let's process default value using associated setter
if (isset($mutators[RecordEntity::MUTATOR_SETTER][$field])) {
try {
$setter = $mutators[RecordEntity::MUTATOR_SETTER][$field];
... | Process value thought associated mutator if any.
@param array $mutators
@param string $field
@param mixed $default
@return mixed |
protected function buildClass($name): string
{
$event = $this->option('event');
if (! starts_with($event, [
$this->rootNamespace(),
'Illuminate',
'\\',
])) {
$event = $this->rootNamespace().'Events\\'.$event;
}
$stub = str_rep... | Build the class with the given name.
@param string $name
@return string |
protected function defaultBuildClass($name): string
{
$stub = $this->files->get($this->getStub());
return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
} | Build the class with the given name.
@param string $name
@return string |
protected function getColumns(): array
{
return [
'name' => ['title' => trans('cortex/foundation::common.name'), 'responsivePriority' => 0],
'file_name' => ['title' => trans('cortex/foundation::common.file_name')],
'mime_type' => ['title' => trans('cortex/foundation::comm... | Get columns.
@return array |
public function onReceive(Server $server, int $fd, int $fromId, string $data)
{
/** @var \Swoft\Rpc\Server\ServiceDispatcher $dispatcher */
$dispatcher = App::getBean('ServiceDispatcher');
$dispatcher->dispatch($server, $fd, $fromId, $data);
} | RPC 请求每次启动一个协程来处理
@param Server $server
@param int $fd
@param int $fromId
@param string $data |
protected function deduplicate(array &$data): bool
{
$criteria = $this->duplicateCriteria($data);
if (isset($this->duplicates[$criteria])) {
//Duplicate is presented, let's reduplicate
$data = $this->duplicates[$criteria];
//Duplicate is presented
re... | In many cases (for example if you have inload of HAS_MANY relation) record data can be
replicated by many result rows (duplicated). To prevent wrong data linking we have to
deduplicate such records. This is only internal loader functionality and required due data
tree are built using php references.
Method will return... |
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Turbolinks-Location', $request->fullUrl());
return $response;
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function connectCommand(string $bucket): void
{
try {
$storageClient = $this->storageFactory->create();
} catch (\Exception $e) {
$this->outputLine('<error>%s</error>', [$e->getMessage()]);
exit(1);
}
$bucketName = $bucket;
$bucket ... | Checks the connection
This command checks if the configured credentials and connectivity allows for connecting with the Google API.
@param string $bucket The bucket which is used for trying to upload and retrieve some test data
@return void |
public function republishCommand(string $collection = 'persistent'): void
{
$collectionName = $collection;
$collection = $this->resourceManager->getCollection($collectionName);
if (!$collection) {
$this->outputLine('<error>The collection %s does not exist.</error>', [$collectionN... | Republish a collection
This command forces publishing resources of the given collection by copying resources from the respective storage
to target bucket.
@param string $collection Name of the collection to publish |
public function setValue($data)
{
if (!in_array($data, static::VALUES)) {
throw new AccessException("Unable to set enum value, invalid value given");
}
$this->value = $data;
$this->changed = true;
} | {@inheritdoc} |
public static function describeColumn(AbstractColumn $column)
{
if (empty(static::VALUES)) {
throw new EnumException("Unable to describe enum column, no values are given");
}
$column->enum(static::VALUES);
if (!empty(static::DEFAULT)) {
$column->defaultValue... | {@inheritdoc} |
public function register(): void
{
! $this->app->runningInConsole() || $this->registerCommands($this->commands);
! $this->app->runningInConsole() || $this->registerCommands($this->devCommands);
} | Register the service provider.
@return void |
protected function registerMigrateMakeCommand(): void
{
$this->app->singleton('command.migrate.make', function ($app) {
// Once we have the migration creator registered, we will create the command
// and inject the creator. The creator is responsible for the actual file
/... | Register the command.
@return void |
public function inverseDefinition(SchemaBuilder $builder, $inverseTo): \Generator
{
if (!is_string($inverseTo)) {
throw new DefinitionException("Inversed relation must be specified as string");
}
foreach ($this->findTargets($builder) as $schema) {
/**
* ... | {@inheritdoc} |
public function packRelation(SchemaBuilder $builder): array
{
$packed = parent::packRelation($builder);
$schema = &$packed[ORMInterface::R_SCHEMA];
//Must be resolved thought builder (can't be defined manually)
$schema[Record::OUTER_KEY] = $this->findOuter($builder)->getName();
... | {@inheritdoc} |
public function getRelated()
{
if ($this->instance instanceof RecordInterface) {
return $this->instance;
}
if (!$this->isLoaded()) {
//Lazy loading our relation data
$this->loadData();
}
if (!empty($this->instance)) {
return $... | {@inheritdoc}
Returns associated parent or NULL if none associated. |
protected function loadData()
{
$this->loaded = true;
$innerKey = $this->key(Record::INNER_KEY);
if (empty($this->parent->getField($innerKey))) {
//Unable to load
return;
}
$selector = $this->orm->selector($this->getClass());
$decorator = new... | {@inheritdoc}
@throws SelectorException
@throws QueryException |
protected function whereStatement(): array
{
return [
$this->key(Record::OUTER_KEY) => $this->parent->getField($this->key(Record::INNER_KEY))
];
} | Where statement to load outer record.
@return array |
public function actions()
{
return [
'error' => [
'class' => ErrorAction::class,
],
'captcha' => [
'class' => CaptchaAction::class,
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor' => 0x222222... | {@inheritdoc} |
public function actionLogout()
{
Yii::$app->user->logout();
$back = Yii::$app->request->post('back') ?: Yii::$app->request->get('back');
return $back ? $this->redirect($back) : $this->goHome();
} | Logout action.
@return string |
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->r... | Displays contact page and sends contact form.
@return string |
public function handle($request, Closure $next)
{
// unBind {locale} route parameter
! $request->route('locale') || $request->route()->forgetParameter('locale');
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function extractRelations(array &$data)
{
//Fetch all relations
$relations = array_intersect_key($data, $this->schema);
foreach ($relations as $name => $relation) {
$this->relations[$name] = $relation;
unset($data[$name]);
}
} | Extract relations data from given entity fields.
@param array $data |
public function queueRelations(ContextualCommandInterface $parent): ContextualCommandInterface
{
if (empty($this->relations)) {
//No relations exists, nothing to do
return $parent;
}
//We have to execute multiple commands at once
$transaction = new Transactio... | Generate command tree with or without relation to parent command in order to specify update
or insert sequence. Commands might define dependencies between each other in order to extend
FK values.
@param ContextualCommandInterface $parent
@return ContextualCommandInterface |
public function get(string $relation): RelationInterface
{
if (isset($this->relations[$relation]) && $this->relations[$relation] instanceof RelationInterface) {
return $this->relations[$relation];
}
$instance = $this->orm->makeRelation($this->class, $relation);
if (array... | Get associated relation instance.
@param string $relation
@return RelationInterface |
protected function leadingRelations()
{
foreach ($this->relations as $relation) {
if ($relation instanceof RelationInterface && $relation->isLeading()) {
yield $relation;
}
}
} | list of relations which lead data of parent record (BELONGS_TO).
Example:
$post = new Post();
$post->user = new User();
@return RelationInterface[]|\Generator |
protected function dependedRelations()
{
foreach ($this->relations as $relation) {
if ($relation instanceof RelationInterface && !$relation->isLeading()) {
yield $relation;
}
}
} | list of loaded relations which depend on parent record (HAS_MANY, MANY_TO_MANY and etc).
Example:
$post = new Post();
$post->comments->add(new Comment());
@return RelationInterface[]|\Generator |
public function withContext(LoaderInterface $parent, array $options = []): LoaderInterface
{
/**
* @var AbstractLoader $parent
* @var self $loader
*/
$loader = parent::withContext($parent, $options);
if ($loader->getDatabase() != $parent->getDatabase()) ... | {@inheritdoc} |
public function isJoined(): bool
{
if (!empty($this->options['using'])) {
return true;
}
return in_array($this->getMethod(), [self::INLOAD, self::JOIN, self::LEFT_JOIN]);
} | Indicated that loaded must generate JOIN statement.
@return bool |
public function isLoaded(): bool
{
return $this->getMethod() !== self::JOIN && $this->getMethod() !== self::LEFT_JOIN;
} | Indication that loader want to load data.
@return bool |
public function loadData(AbstractNode $node)
{
if ($this->isJoined() || !$this->isLoaded()) {
//Loading data for all nested relations
parent::loadData($node);
return;
}
$references = $node->getReferences();
if (empty($references)) {
/... | {@inheritdoc} |
protected function configureQuery(SelectQuery $query, bool $loadColumns = true, array $outerKeys = []): SelectQuery
{
if ($loadColumns) {
if ($this->isJoined()) {
//Mounting columns
$this->mountColumns($query, $this->options['minify']);
} else {
... | Configure query with conditions, joins and columns.
@param SelectQuery $query
@param bool $loadColumns
@param array $outerKeys Set of OUTER_KEY values collected by parent loader.
@return SelectQuery |
protected function getAlias(): string
{
if (!empty($this->options['using'])) {
//We are using another relation (presumably defined by with() to load data).
return $this->options['using'];
}
if (!empty($this->options['alias'])) {
return $this->options['ali... | Relation table alias.
@return string |
protected function localKey($key)
{
if (empty($this->schema[$key])) {
return null;
}
return $this->getAlias() . '.' . $this->schema[$key];
} | Generate sql identifier using loader alias and value from relation definition. Key name to be
fetched from schema.
Example:
$this->getKey(Record::OUTER_KEY);
@param string $key
@return string|null |
protected function ensureAlias(AbstractLoader $parent)
{
//Let's calculate loader alias
if (empty($this->options['alias'])) {
if ($this->isLoaded() && $this->isJoined()) {
//Let's create unique alias, we are able to do that for relations just loaded
$this-... | Ensure table alias.
@param AbstractLoader $parent |
public function publishCollection(CollectionInterface $collection)
{
$storage = $collection->getStorage();
$targetBucket = $this->getCurrentBucket();
if ($storage instanceof GcsStorage && $storage->getBucketName() === $targetBucket->name()) {
// Nothing to do: the storage bucket... | Publishes the whole collection to this target
@param CollectionInterface $collection The collection to publish
@throws \Exception
@throws \Neos\Flow\Exception |
public function getPublicStaticResourceUri($relativePathAndFilename)
{
$relativePathAndFilename = $this->encodeRelativePathAndFilenameForUri($relativePathAndFilename);
return 'https://storage.googleapis.com/' . $this->bucketName . '/'. $this->keyPrefix . $relativePathAndFilename;
} | Returns the web accessible URI pointing to the given static resource
@param string $relativePathAndFilename Relative path and filename of the static resource
@return string The URI |
public function unpublishResource(PersistentResource $resource)
{
$collection = $this->resourceManager->getCollection($resource->getCollectionName());
$storage = $collection->getStorage();
if ($storage instanceof GcsStorage && $storage->getBucketName() === $this->bucketName) {
//... | Unpublishes the given persistent resource
@param \Neos\Flow\ResourceManagement\PersistentResource $resource The resource to unpublish
@throws \Exception |
public function getPublicPersistentResourceUri(PersistentResource $resource)
{
$relativePathAndFilename = $this->encodeRelativePathAndFilenameForUri($this->getRelativePublicationPathAndFilename($resource));
if ($this->baseUri != '') {
return $this->baseUri . $relativePathAndFilename;
... | Returns the web accessible URI pointing to the specified persistent resource
@param \Neos\Flow\ResourceManagement\PersistentResource $resource PersistentResource object or the resource hash of the resource
@return string The URI |
protected function getRelativePublicationPathAndFilename(ResourceMetaDataInterface $object)
{
if ($object->getRelativePublicationPath() !== '') {
$pathAndFilename = $object->getRelativePublicationPath() . $object->getFilename();
} else {
$pathAndFilename = $object->getSha1() ... | Determines and returns the relative path and filename for the given Storage Object or PersistentResource. If the given
object represents a persistent resource, its own relative publication path will be empty. If the given object
represents a static resources, it will contain a relative path.
@param ResourceMetaDataInt... |
public function doHandler(ServerRequestInterface $request, array $handler): Response
{
// the function params of service
$data = $request->getAttribute(PackerMiddleware::ATTRIBUTE_DATA);
$params = $data['params'] ?? [];
list($serviceClass, $method) = $handler;
$service = App... | Execute service handler
@param \Psr\Http\Message\ServerRequestInterface $request
@param array $handler
@return Response |
public function getClass(): string
{
if (empty($parentType = $this->parent->getField($this->key(Record::MORPH_KEY)))) {
return parent::getClass();
}
//Resolve parent using role map
return $this->schema[Record::MORPHED_ALIASES][$parentType];
} | {@inheritdoc} |
public function setRelated($value)
{
//Make sure value is accepted
$this->assertValid($value);
$this->loaded = true;
$this->instance = $value;
} | {@inheritdoc} |
public function queueCommands(ContextualCommandInterface $parentCommand): CommandInterface
{
if (!empty($this->instance)) {
return $this->queueRelated($parentCommand);
}
if (!$this->schema[Record::NULLABLE]) {
throw new RelationException("No data presented in non nul... | @param ContextualCommandInterface $parentCommand
@return CommandInterface
@throws RelationException |
private function queueRelated(
ContextualCommandInterface $parentCommand
): ContextualCommandInterface {
/*
* Only queue parent relations when parent wasn't saved already, attention, this might
* cause an issues with very deep recursive structures (and it's expected).
*/
... | Store related instance
@param ContextualCommandInterface $parentCommand
@return ContextualCommandInterface |
public function up(): void
{
Schema::create(config('cortex.foundation.tables.notifications'), function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('type');
$table->morphs('notifiable');
$table->{$this->jsonable()}('data');
$t... | Run the migrations.
@return void |
public function getName(): string
{
if (!empty($this->name)) {
return $this->name;
}
$name = ($this->isUnique() ? 'unique_' : 'index_') . join('_', $this->getColumns());
return strlen($name) > 64 ? md5($name) : $name;
} | Generate unique index name.
@return string |
public function up()
{
Schema::create(config('cortex.foundation.tables.activity_log'), function (Blueprint $table) {
// Columns
$table->increments('id');
$table->string('log_name');
$table->string('description');
$table->integer('subject_id')->null... | Run the migrations. |
protected function mountColumns(
SelectQuery $query,
bool $minify = false,
string $prefix = '',
bool $overwrite = false
) {
//Column source alias
$alias = $this->getAlias();
$columns = $overwrite ? [] : $query->getColumns();
foreach ($this->getColumns... | Set columns into SelectQuery.
@param SelectQuery $query
@param bool $minify Minify column names (will work in case when query parsed in
FETCH_NUM mode).
@param string $prefix Prefix to be added for each column name.
@param bool $overwrite When set to true existed columns will be removed. |
public function withContext(RelationContext $source, RelationContext $target = null): self
{
$definition = clone $this;
$definition->sourceContext = $source;
$definition->targetContext = $target;
return $definition;
} | Set relation contexts.
@param RelationContext $source
@param RelationContext|null $target
@return RelationDefinition |
public function locateSchemas(): array
{
if (!$this->container->has(ClassesInterface::class)) {
return [];
}
/**
* @var ClassesInterface $classes
*/
$classes = $this->container->get(ClassesInterface::class);
$schemas = [];
foreach ($cla... | Locate all available document schemas in a project.
@return SchemaInterface[] |
public function locateSources(): array
{
if (!$this->container->has(ClassesInterface::class)) {
return [];
}
/**
* @var ClassesInterface $classes
*/
$classes = $this->container->get(ClassesInterface::class);
$result = [];
foreach ($clas... | Locate all DocumentSources defined by user. Must return values in a form of
Document::class => Source::class.
@return array |
public function registerRelation(SchemaBuilder $builder, RelationDefinition $definition)
{
if (!$this->config->hasRelation($definition->getType())) {
throw new DefinitionException(sprintf(
"Undefined relation type '%s' in '%s'.'%s'",
$definition->getType(),
... | Registering new relation definition. At this moment function would not check if relation is
unique and will redeclare it.
@param SchemaBuilder $builder
@param RelationDefinition $definition Relation options (definition).
@throws DefinitionException |
public function inverseRelations(SchemaBuilder $builder)
{
/**
* Inverse process is relation specific.
*/
foreach ($this->relations as $relation) {
$definition = $relation->getDefinition();
if ($definition->needInversion()) {
if (!$relation ... | Create inverse relations where needed.
@param SchemaBuilder $builder
@throws DefinitionException |
public function declareTables(SchemaBuilder $builder): \Generator
{
foreach ($this->relations as $relation) {
foreach ($relation->declareTables($builder) as $table) {
yield $table;
}
}
} | Declare set of tables for each relation. Method must return Generator of AbstractTable
sequentially (attention, non sequential processing will cause collision issues between
tables).
@param SchemaBuilder $builder
@return \Generator |
public function packRelations(string $class, SchemaBuilder $builder): array
{
$result = [];
foreach ($this->relations as $relation) {
$definition = $relation->getDefinition();
if ($definition->sourceContext()->getClass() == $class) {
//Packing relation, relat... | Pack relation schemas for specific model class in order to be saved in memory.
@param string $class
@param SchemaBuilder $builder
@return array |
protected function locateOuter(
SchemaBuilder $builder,
RelationDefinition $definition
): RelationDefinition {
/**
* todo: add functionality to resolve database alias
*/
if (!empty($definition->targetContext())) {
//Nothing to do, already have outer par... | Populate entity target based on interface or role.
@param SchemaBuilder $builder
@param \Spiral\ORM\Schemas\Definitions\RelationDefinition $definition
@return \Spiral\ORM\Schemas\Definitions\RelationDefinition
@throws DefinitionException |
private function matchBinded(string $target, SchemaInterface $schema): bool
{
if ($schema->getRole() == $target) {
return true;
}
if (interface_exists($target) && is_a($schema->getClass(), $target, true)) {
//Match by interface
return true;
}
... | Check if schema matches relation target.
@param string $target
@param \Spiral\ORM\Schemas\SchemaInterface $schema
@return bool |
public function authorizeGeneric($resource): void
{
$middleware = [];
foreach ($this->mapResourceAbilities() as $method => $ability) {
$middleware["can:{$resource}"][] = $method;
}
foreach ($middleware as $middlewareName => $methods) {
$this->middleware($mid... | {@inheritdoc} |
protected function mapResourceAbilities(): array
{
// Reflect calling controller
$controller = new ReflectionClass(static::class);
// Get public methods and filter magic methods
$methods = array_filter($controller->getMethods(ReflectionMethod::IS_PUBLIC), function ($item) use ($cont... | Map resource actions to resource abilities.
@throws \ReflectionException
@return array |
public function setRelated($value)
{
$this->loadData(true);
if (is_null($value)) {
$value = [];
}
if (!is_array($value)) {
throw new RelationException("HasMany relation can only be set with array of entities");
}
//Do not add items twice
... | {@inheritdoc}
@throws RelationException |
public function add(RecordInterface $record): self
{
$this->assertValid($record);
$this->loadData(true)->instances[] = $record;
return $this;
} | Add new record into entity set. Attention, usage of this method WILL load relation data
unless partial.
@param RecordInterface $record
@return self
@throws RelationException |
public function delete(RecordInterface $record): self
{
$this->loadData(true);
$this->assertValid($record);
foreach ($this->instances as $index => $instance) {
if ($this->match($instance, $record)) {
//Remove from save
unset($this->instances[$inde... | Delete one record, strict compaction, make sure exactly same instance is given.
@param RecordInterface $record
@return self
@throws RelationException |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.