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 following form: * * [type => target, option => value, option => value] */ $type = key($definition); $target = $definition[$type]; unset($definition[$type]); //Defining relation yield new RelationDefinition( $name, $type, $target, $definition, $definition[Record::INVERSE] ?? null ); } }
{@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 behaviour RecordEntity::SH_SECURED => $this->reflection->getSecured(), RecordEntity::SH_FILLABLE => $this->reflection->getFillable(), //Mutators can be altered based on ORM\SchemasConfig RecordEntity::SH_MUTATORS => $this->buildMutators($table), ]; }
{@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 = $column->getDefaultValue(); //For non null values let's apply mutators to typecast it if (!is_null($default) && !is_object($default) && !$column->isNullable()) { $default = $this->mutateValue($mutators, $field, $default); } $defaults[$field] = $default; } return $defaults; }
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($filter = $this->mutatorsConfig->getMutators($column->abstractType()))) { //Mutator associated with type directly $resolved += $filter; } elseif (!empty($filter = $this->mutatorsConfig->getMutators('php:' . $column->phpType()))) { //Mutator associated with php type $resolved += $filter; } //Merging mutators and default mutators foreach ($resolved as $mutator => $filter) { if (!array_key_exists($column->getName(), $mutators[$mutator])) { $mutators[$mutator][$column->getName()] = $filter; } } } foreach ($this->getFields() as $field => $type) { if ( class_exists($type) && is_a($type, RecordAccessorInterface::class, true) ) { //Direct column accessor definition $mutators['accessor'][$field] = $type; } } return $mutators; }
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); if (!is_string($value) || empty($value)){ throw new DefinitionException( "Record '{$this}' has index definition with invalid index name" ); } $name = $value; continue; } if ($value == RecordEntity::INDEX || $value == RecordEntity::UNIQUE) { $unique = ($value === RecordEntity::UNIQUE); continue; } $columns[] = $value; } if (is_null($unique)) { throw new DefinitionException( "Record '{$this}' has index definition with unspecified index type" ); } if (empty($columns)) { throw new DefinitionException( "Record '{$this}' has index definition without any column associated to" ); } return new IndexDefinition($columns, $unique, $name); }
@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]; $default = call_user_func($setter, $default); return $default; } catch (\Exception $exception) { //Unable to generate default value, use null or empty array as fallback } } if (isset($mutators[RecordEntity::MUTATOR_ACCESSOR][$field])) { $default = $this->accessorDefault( $default, $mutators[RecordEntity::MUTATOR_ACCESSOR][$field] ); return $default; } return $default; }
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_replace( 'DummyEvent', class_basename($event), $this->defaultBuildClass($name) ); return str_replace( 'DummyFullEvent', $event, $stub ); }
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::common.mime_type')], 'size' => ['title' => trans('cortex/foundation::common.size')], 'created_at' => ['title' => trans('cortex/foundation::common.created_at'), 'render' => "moment(data).format('YYYY-MM-DD, hh:mm:ss A')"], 'updated_at' => ['title' => trans('cortex/foundation::common.updated_at'), 'render' => "moment(data).format('YYYY-MM-DD, hh:mm:ss A')"], 'delete' => ['title' => trans('cortex/foundation::common.delete'), 'orderable' => false, 'searchable' => false, 'render' => '"<a href=\"#\" data-toggle=\"modal\" data-target=\"#delete-confirmation\" data-modal-action=\""+data+"\" data-modal-title=\"" + Lang.trans(\'cortex/foundation::messages.delete_confirmation_title\') + "\" data-modal-button=\"<a href=\'#\' class=\'btn btn-danger\' data-form=\'delete\' data-token=\''.csrf_token().'\'><i class=\'fa fa-trash-o\'></i> \"" + Lang.trans(\'cortex/foundation::common.delete\') + "\"</a>\" data-modal-body=\"" + Lang.trans(\'cortex/foundation::messages.delete_confirmation_body\', {type: \'media\', name: full.name}) + "\" title=\"" + Lang.trans(\'cortex/foundation::common.delete\') + "\"><i class=\"fa fa-trash text-danger\"></i></a>"'], ]; }
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 return false; } //Remember record to prevent future duplicates $this->duplicates[$criteria] = &$data; return true; }
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 true if data is unique handled before and false in opposite case. Provided data array will be automatically linked with it's unique state using references. @param array $data Reference to parsed record data, reference will be pointed to valid and existed data segment if such data was already parsed. @return bool
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 = $storageClient->bucket($bucketName); $this->outputLine('Writing test object into bucket (%s) ...', [$bucketName]); $bucket->upload( 'test', [ 'name' => 'Flownative.Google.CloudStorage.ConnectionTest.txt', 'metadata' => [ 'test' => true ] ] ); $this->outputLine('Retrieving test object from bucket ...'); $this->outputLine('<em>' . $bucket->object('Flownative.Google.CloudStorage.ConnectionTest.txt')->downloadAsString() . '</em>'); $this->outputLine('Deleting test object from bucket ...'); $bucket->object('Flownative.Google.CloudStorage.ConnectionTest.txt')->delete(); $this->outputLine('OK'); }
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>', [$collectionName]); exit(1); } $target = $collection->getTarget(); if (!$target instanceof GcsTarget) { $this->outputLine('<error>The target defined in collection %s is not a Google Cloud Storage target.</error>', [$collectionName]); exit(1); } $this->outputLine('Republishing collection ...'); $this->output->progressStart(); try { foreach ($collection->getObjects() as $object) { /** @var StorageObject $object */ $resource = $this->resourceManager->getResourceBySha1($object->getSha1()); if ($resource) { $target->publishResource($resource, $collection); } $this->output->progressAdvance(); } } catch (\Exception $e) { $this->outputLine('<error>Publishing failed</error>'); $this->outputLine($e->getMessage()); $this->outputLine(get_class($e)); exit(2); } $this->output->progressFinish(); $this->outputLine(); }
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(static::DEFAULT)->nullable(false); } }
{@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 // creation of the migrations, and may be extended by these developers. $creator = $app['migration.creator']; $composer = $app['composer']; return new MigrateMakeCommand($creator, $composer); }); }
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) { /** * We are going to simply replace outer key with inner key and keep the rest of options intact. */ $inversed = new RelationDefinition( $inverseTo, Record::MANY_TO_MANY, $this->definition->sourceContext()->getClass(), [ Record::PIVOT_TABLE => $this->option(Record::PIVOT_TABLE), Record::OUTER_KEY => $this->option(Record::INNER_KEY), Record::INNER_KEY => $this->findOuter($builder)->getName(), Record::THOUGHT_INNER_KEY => $this->option(Record::THOUGHT_OUTER_KEY), Record::THOUGHT_OUTER_KEY => $this->option(Record::THOUGHT_INNER_KEY), Record::CREATE_CONSTRAINT => false, Record::CREATE_INDEXES => $this->option(Record::CREATE_INDEXES), Record::CREATE_PIVOT => false, //Table creation hes been already handled //We have to include morphed key in here Record::PIVOT_COLUMNS => $this->option(Record::PIVOT_COLUMNS) + [ $this->option(Record::MORPH_KEY) => 'string' ], Record::WHERE_PIVOT => $this->option(Record::WHERE_PIVOT), Record::MORPH_KEY => $this->option(Record::MORPH_KEY) ] ); //In back order :) yield $inversed->withContext( RelationContext::createContent( $schema, $builder->requestTable($schema->getTable(), $schema->getDatabase()) ), $this->definition->sourceContext() ); } }
{@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(); //Clarifying location $schema[Record::PIVOT_DATABASE] = $this->definition->sourceContext()->getDatabase(); $schema[Record::PIVOT_COLUMNS] = array_keys($schema[Record::PIVOT_COLUMNS]); //Ensure that inner keys are always presented $schema[Record::PIVOT_COLUMNS] = array_merge( [ $this->option(Record::THOUGHT_INNER_KEY), $this->option(Record::THOUGHT_OUTER_KEY), $this->option(Record::MORPH_KEY) ], $schema[Record::PIVOT_COLUMNS] ); //Model-role mapping foreach ($this->findTargets($builder) as $outer) { /* * //Must be pluralized * $tag->tagged->posts->count(); */ $role = Inflector::pluralize($outer->getRole()); //Role => model mapping $schema[Record::MORPHED_ALIASES][$role] = $outer->getClass(); } return $packed; }
{@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 $this->instance; } if (!empty($this->data)) { $this->instance = $this->orm->make( $this->getClass(), $this->data, ORMInterface::STATE_LOADED, true ); } elseif ($this->isPlaceholderNeeded()) { //Stub instance $this->instance = $this->orm->make( $this->getClass(), [], ORMInterface::STATE_NEW ); } return $this->instance; }
{@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 AliasDecorator($selector, 'where', $selector->getAlias()); $decorator->where($this->whereStatement()); $this->data = $selector->fetchData(); if (!empty($this->data[0])) { //Use first result $this->data = $this->data[0]; } }
{@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, 'foreColor' => 0xFFFFFF, ], 'index' => [ 'class' => RenderAction::class, 'data' => function () { return ['contactForm' => new ContactForm()]; }, ], 'about' => [ 'class' => RenderAction::class, ], 'policy' => [ 'class' => RenderAction::class, ], 'contact' => [ 'class' => ContactAction::class, ], ]; }
{@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->render('contact', compact('model')); }
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 TransactionalCommand(); foreach ($this->leadingRelations() as $relation) { //Generating commands needed to save given relation prior to parent command if ($relation->isLoaded()) { $transaction->addCommand($relation->queueCommands($parent)); } } //Parent model save operations (true state that this is leading/primary command) $transaction->addCommand($parent, true); foreach ($this->dependedRelations() as $relation) { //Generating commands needed to save relations after parent command being executed if ($relation->isLoaded()) { $transaction->addCommand($relation->queueCommands($parent)); } } return $transaction; }
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_key_exists($relation, $this->relations)) { //Indicating that relation is loaded $instance = $instance->withContext($this->parent, true, $this->relations[$relation]); } else { //Not loaded relation $instance = $instance->withContext($this->parent, false); } return $this->relations[$relation] = $instance; }
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()) { if ($loader->isJoined()) { throw new LoaderException('Unable to join tables located in different databases'); } //Loader is not joined, let's make sure that POSTLOAD is used if ($this->isLoaded()) { $loader->options['method'] = self::POSTLOAD; } } //Calculate table alias $loader->ensureAlias($parent); return $loader; }
{@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)) { //Nothing found at parent level, unable to create sub query return; } //Ensure all nested relations $statement = $this->configureQuery($this->createQuery(), true, $references)->run(); $statement->setFetchMode(\PDO::FETCH_NUM); foreach ($statement as $row) { $node->parseRow(0, $row); } $statement->close(); //Loading data for all nested relations parent::loadData($node); }
{@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 { //This is initial set of columns (remove all existed) $this->mountColumns($query, $this->options['minify'], '', true); } } return parent::configureQuery($query); }
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['alias']; } throw new LoaderException("Unable to resolve loader alias"); }
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->options['alias'] = 'd' . decoct(++self::$countLevels); } else { //Let's use parent alias to continue chain $this->options['alias'] = $parent->getAlias() . '_' . $this->relation; } } }
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 is (or should be) publicly accessible return; } if (!isset($this->existingObjectsInfo)) { $this->existingObjectsInfo = []; $parameters = [ 'prefix' => $this->keyPrefix ]; foreach ($this->getCurrentBucket()->objects($parameters) as $storageObject) { /** @var StorageObject $storageObject */ $this->existingObjectsInfo[$storageObject->name()] = true; } } $obsoleteObjects = $this->existingObjectsInfo; if ($storage instanceof GcsStorage) { $this->publishCollectionFromDifferentGoogleCloudStorage($collection, $storage, $this->existingObjectsInfo, $obsoleteObjects, $targetBucket); } else { foreach ($collection->getObjects() as $object) { /** @var \Neos\Flow\ResourceManagement\Storage\StorageObject $object */ $this->publishFile($object->getStream(), $this->getRelativePublicationPathAndFilename($object), $object); unset($obsoleteObjects[$this->getRelativePublicationPathAndFilename($object)]); } } $this->systemLogger->log(sprintf('Removing %s obsolete objects from target bucket "%s".', count($obsoleteObjects), $this->bucketName), LOG_INFO); foreach (array_keys($obsoleteObjects) as $relativePathAndFilename) { try { $targetBucket->object($this->keyPrefix . $relativePathAndFilename)->delete(); } catch (NotFoundException $e) { } } }
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) { // Unpublish for same-bucket setups is a NOOP, because the storage object will already be deleted. return; } try { $objectName = $this->keyPrefix . $this->getRelativePublicationPathAndFilename($resource); $this->getCurrentBucket()->object($objectName)->delete(); $this->systemLogger->log(sprintf('Successfully unpublished resource as object "%s" (MD5: %s) from bucket "%s"', $objectName, $resource->getMd5() ?: 'unknown', $this->bucketName), LOG_DEBUG); } catch (NotFoundException $e) { } }
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; } else { return 'https://storage.googleapis.com/' . $this->bucketName . '/'. $this->keyPrefix . $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() . '/' . $object->getFilename(); } return $pathAndFilename; }
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 ResourceMetaDataInterface $object PersistentResource or Storage Object @return string The relative path and filename, for example "c828d0f88ce197be1aff7cc2e5e86b1244241ac6/MyPicture.jpg"
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::getBean($serviceClass); // execute handler with params $response = PhpHelper::call([$service, $method], $params); $response = ResponseHelper::formatData($response); // response if (! $response instanceof Response) { $response = (new Response())->withAttribute(self::ATTRIBUTE, $response); } return $response; }
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 nullable relation"); } $parentCommand->addContext($this->schema[Record::INNER_KEY], null); $parentCommand->addContext($this->schema[Record::MORPH_KEY], null); return new NullCommand(); }
@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). */ $innerCommand = $this->instance->queueStore( !$this->instance->isLoaded() ); if (!$this->isSynced($this->parent, $this->instance)) { //Syncing FKs before primary command been executed $innerCommand->onExecute(function ($innerCommand) use ($parentCommand) { $parentCommand->addContext( $this->key(Record::INNER_KEY), $this->lookupKey(Record::OUTER_KEY, $this->parent, $innerCommand) ); //Morph key value $parentCommand->addContext( $this->key(Record::MORPH_KEY), $this->orm->define(get_class($this->instance), ORMInterface::R_ROLE_NAME) ); }); } return $innerCommand; }
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'); $table->timestamp('read_at')->nullable(); $table->timestamps(); }); }
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')->nullable(); $table->string('subject_type')->nullable(); $table->integer('causer_id')->nullable(); $table->string('causer_type')->nullable(); $table->{$this->jsonable()}('properties')->nullable(); $table->timestamps(); // Indexes $table->index('log_name'); }); }
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() as $name) { $column = $name; if ($minify) { //Let's use column number instead of full name $column = 'c' . count($columns); } $columns[] = "{$alias}.{$name} AS {$prefix}{$column}"; } //Updating column set $query->columns($columns); }
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 ($classes->getClasses(RecordEntity::class) as $class) { if ($class['abstract']) { continue; } $schemas[] = $this->container->get(FactoryInterface::class)->make( RecordSchema::class, ['reflection' => new ReflectionEntity($class['name']),] ); } return $schemas; }
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 ($classes->getClasses(RecordSource::class) as $class) { $source = $class['name']; if ($class['abstract'] || empty($source::RECORD)) { continue; } $result[$source::RECORD] = $source; } return $result; }
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(), $definition->sourceContext()->getClass(), $definition->getName() )); } if ($definition->isLateBinded()) { /** * Late binded relations locate their parent based on all existed records. */ $definition = $this->locateOuter($builder, $definition); } $class = $this->config->relationClass( $definition->getType(), RelationsConfig::SCHEMA_CLASS ); //Creating relation schema $relation = $this->factory->make($class, compact('definition')); $this->relations[] = $relation; }
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 instanceof InversableRelationInterface) { throw new DefinitionException(sprintf( "Unable to inverse relation '%s'.'%s', relation schema '%s' is non inversable", $definition->sourceContext()->getClass(), $definition->getName(), get_class($relation) )); } $inversed = $relation->inverseDefinition($builder, $definition->getInverse()); foreach ($inversed as $definition) { $this->registerRelation($builder, $definition); } } } }
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, relation schema are given with associated table $result[$definition->getName()] = $relation->packRelation($builder); } } return $result; }
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 parent return $definition; } $found = null; foreach ($builder->getSchemas() as $schema) { if ($this->matchBinded($definition->getTarget(), $schema)) { if (!empty($found)) { //Multiple records found throw new DefinitionException(sprintf( "Ambiguous target of '%s' for late binded relation %s.%s", $definition->getTarget(), $definition->sourceContext()->getClass(), $definition->getName() )); } $found = $schema; } } if (empty($found)) { throw new DefinitionException(sprintf( "Unable to locate outer record of '%s' for late binded relation %s.%s", $definition->getTarget(), $definition->sourceContext()->getClass(), $definition->getName() )); } return $definition->withContext( $definition->sourceContext(), RelationContext::createContent( $found, $builder->requestTable($found->getTable(), $found->getDatabase()) ) ); }
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; } return false; }
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($middlewareName)->only($methods); } }
{@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 ($controller) { return $item->class === $controller->name && mb_substr($item->name, 0, 2) !== '__' && ! in_array($item->name, $this->resourceActionWhitelist); }); // Get controller actions $actions = array_combine($items = array_map(function ($action) { return $action->name; }, $methods), $items); // Map resource actions to resourse abilities array_walk($actions, function ($value, $key) use (&$actions) { $actions[$key] = array_get($this->resourceAbilityMap(), $key, $value); }); return $actions; }
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 $matched = []; foreach ($value as $index => $item) { if (is_null($item)) { unset($value[$index]); continue; } $this->assertValid($item); if (!empty($instance = $this->matchOne($item))) { $matched[] = $instance; unset($value[$index]); } } $this->deleteInstances = array_diff($this->instances, $matched); $this->instances = $matched + $value; }
{@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[$index]); $this->deleteInstances[] = $instance; break; } } $this->instances = array_values($this->instances); return $this; }
Delete one record, strict compaction, make sure exactly same instance is given. @param RecordInterface $record @return self @throws RelationException