@param BlockOwnerInterface $owner
@param string              $type
@param integer             $parentId
@param integer             $placeholder
@param array               $sort
@param null|array          $data

@throws \Exception

@return BlockInterface
8383
public function createBlock($owner, $type, $parentId, $placeholder, $sort, $data = null, $draft = true)
    {
        /** @var AbstractBlockService $service */
        $service = $this->getService($type);
        $parent = $parentId ? $this->find($parentId, $draft) : null;

        // This should replaced with a more hardened function
        if (is_null($data)) {
            $data = array();
        }
        $data['owner'] = $owner;

        $block = $service->createBlock($data);

        $block->setPosition($placeholder);
        $block->setSort(0); // < default, gets recalculated later for entire level
        $block->setSortParent(-1); // < need to be calculated when putting in the tree

        // Set owner
        if (is_null($parent) || false === $parent->isShared()) {
            $block->setOwner($owner);
        }

        $block->setParent($parent);

        // Save now, rest will be in changeset. All we do is a create a stub entry anyway.
        $this->save($block, $draft);

        if (count($sort) > 1) {
            // Replace the zero value in the posted sort array
            // with the newly created id to perform sorting
            $id = $block->getId();
            $sort = array_map(
                function ($v) use ($id) {
                    return $v == "" || $v == "0" ? $id : $v;
                },
                $sort
            );

            array_walk($sort, function (&$id) { $id = (int) $id; });
            $contained = $this->findById($sort, $draft);

            if ($contained) {
                $contained = $this->setSortsByDirective($contained, $sort);

                foreach ($contained as $node) {
                    // If nodes are in the same parent and if their owners match we
                    // save the changes. We don't want to save sort changes made to
                    // nodes belonging to inherited trees.
                    if ($node->getParent() === $block->getParent() &&
                        (($node->getOwner() === null && $block->getOwner() === null) ||
                        ($node->getOwner()->getId() == $block->getOwner()->getId()))) {
                        $this->save($node, $draft);
                    }
                }
            }
        }

        return $block;
    }
1258822
public function setOwner(HTML_QuickForm2_Node $owner)
    {
        if (!$owner instanceof HTML_QuickForm2_Element_InputFile) {
            throw new HTML_QuickForm2_InvalidArgumentException(
                'MimeType Rule can only validate file upload fields, '.
                get_class($owner) . ' given'
            );
        }
        parent::setOwner($owner);
    }
229838
public function viewBlockAction($type, $typeId, $id)
    {
        $this->getDoctrine()->getManager()->getFilters()->disable('draftversion');

        /** @var BlockManager $manager */
        $manager = $this->get('opifer.content.block_manager');

        /** @var Environment $environment */
        $environment = $this->get(sprintf('opifer.content.block_%s_environment', $type));
        $version = $manager->getNewVersion($id);

        $environment->load($typeId)->setVersion($version);

        $block = $environment->getBlock($id);

        $environment->setBlockMode('manage');

        $service = $manager->getService($block);

        $this->get('opifer.content.twig.content_extension')->setBlockEnvironment($environment);


        return new JsonResponse(['view' => $service->manage($block)->getContent()]);
    }
1125913
public function sortBlocks(array $blocks)
    {
        // Perform a simple sort first
        usort($blocks, function ($a, $b)  {
            if ($a->getSort() == $b->getSort()) {
                return 0;
            }
            return ($a->getSort() < $b->getSort()) ? -1 : 1;
        });

        // Determine hierarchy of ownership first
        $ownerIds = array();
        foreach ($blocks as $block) {
            $superKey = ($block->getOwner()->getSuper()) ? array_search($block->getOwner()->getSuper()->getId(), $ownerIds) : false;
            if ($superKey === false) {
                array_unshift($ownerIds, $block->getOwner()->getId());
            } else {
                $ownerIds = array_merge(array_slice($ownerIds, 0, $superKey+1), array($block->getOwner()->getId()), array_slice($ownerIds, $superKey+1));
            }
        }
        $ownerIds = array_flip($ownerIds); // Flip it for easier lookup by parentId as key.
        asort($ownerIds);

        $sorted = array();
        $parentOwnerId = null;
        $parentSize = null;
        foreach ($ownerIds as $ownerId => $ownerPos) {
            // Get blocks in level/segment
            $segment = array_values(array_filter($blocks, function ($block) use ($ownerId) {
                return ($block->getOwner() && $block->getOwner()->getId() == $ownerId);
            }));

            if (! count($segment)) {
                $parentOwnerId = $ownerId;
                continue; // nothing to do for this owner
            }

            // now inject at correct positions
            if (count($segment) && $parentOwnerId === null) {
                $sorted = $segment;
            } else if (count($segment)) {
                $positioned = array_filter($segment, function ($block) {
                   return ($block->getSortParent() !== null && $block->getSortParent() >= 0);
                });

                // if nothing is positioned throw them on top
                if (! count($positioned)) {
                    $sorted = array_merge($segment, $sorted);
                } else {
                    // first part
                    $keys = array_keys($positioned);
                    if ($keys[0] > 0) {
                        $sorted = array_merge(array_slice($segment, 0, array_shift($keys)), $sorted);
                    } elseif ($keys[0] == 0) {
                        unset($keys[0]);
                    }

                    foreach ($positioned as $key => $block) {
                        $endIdx = (count($keys)) ? array_shift($keys) : null;
                        $insert = array_slice($segment, $key, ($endIdx) ? ($endIdx-$key) : null);

                        foreach ($sorted as $insertIdx => $item) {
                            // Check if we inherit from this block
                            if ($item->getOwner()->getId() == $parentOwnerId && $item->getSort() == $block->getSortParent() &&
                                // And check if we're in the same parent block on same position
                                (($item->isInRoot() && $block->isInRoot() || ($item->getParent() && $block->getParent() && $item->getParent()->getId() == $block->getParent()->getId())) && $item->getPosition() == $block->getPosition())) {
                                break;
                            }
                        }
                        $sorted = array_merge(array_slice($sorted, 0, $insertIdx+1), $insert, array_slice($sorted, $insertIdx+1));
                    }
                }
            }

            $parentOwnerId = $ownerId;
        }

        return $sorted;
    }
1014156
public static function getAndAssertActiveBlock($type)
    {
        $active_block = static::getActive();
        $current = get_class($active_block->activeBlock());
        if ( !is_a($active_block->activeBlock(), $type)) {
            throw new Exception("Improperly nested block. Expected a $type, got a $current");
        }
        return $active_block;
    }
198717
public function scopeWhereNotOwnedBy(Builder $query, CanBeOwnerContract $owner)
    {
        return $query->where(function (Builder $q) use ($owner) {
            $q->where('owned_by_id', '!=', $owner->getKey())
                ->orWhere('owned_by_type', '!=', $owner->getMorphClass());
        });
    }
113487
public static function getParent(BlockView $view, $type)
    {
        $parent = null;

        if (null !== $view->parent) {
            if (static::isType($view->parent, $type)) {
                $parent = $view->parent;
            } else {
                $parent = static::getParent($view->parent, $type);
            }
        }

        return $parent;
    }
1027013
public function update($owner, $eventId, array $data)
    {
        $data = self::mergeData($data, [
            'owner' => $owner,
            'contactEvent' => [
                'eventId' => $eventId,
            ],
        ]);

        return $this->client->doPost('contact/updateContactExtEvent', $data);
    }
226009
public function viewAction($owner, $ownerId)
    {
        /** @var BlockProviderInterface $provider */
        $provider = $this->get('opifer.content.block_provider_pool')->getProvider($owner);
        $object = $provider->getBlockOwner($ownerId);

        /** @var Environment $environment */
        $environment = $this->get('opifer.content.block_environment');
        $environment->setDraft(true)->setObject($object);
        $environment->setBlockMode('manage');

        return $this->render($environment->getView(), $environment->getViewParameters());
    }
1167310
private function internalCreateBlock(
        APIBlockCreateStruct $blockCreateStruct,
        PersistenceBlock $targetBlock,
        string $placeholder,
        ?int $position = null
    ): Block {
        $persistenceLayout = $this->layoutHandler->loadLayout($targetBlock->layoutId, Value::STATUS_DRAFT);

        $createdBlock = $this->transaction(
            function () use ($blockCreateStruct, $persistenceLayout, $targetBlock, $placeholder, $position): PersistenceBlock {
                $blockDefinition = $blockCreateStruct->getDefinition();

                $createdBlock = $this->blockHandler->createBlock(
                    BlockCreateStruct::fromArray(
                        [
                            'status' => $targetBlock->status,
                            'position' => $position,
                            'definitionIdentifier' => $blockDefinition->getIdentifier(),
                            'viewType' => $blockCreateStruct->viewType,
                            'itemViewType' => $blockCreateStruct->itemViewType,
                            'name' => $blockCreateStruct->name,
                            'alwaysAvailable' => $blockCreateStruct->alwaysAvailable,
                            'isTranslatable' => $blockCreateStruct->isTranslatable,
                            'parameters' => iterator_to_array(
                                $this->parameterMapper->serializeValues(
                                    $blockDefinition,
                                    $blockCreateStruct->getParameterValues()
                                )
                            ),
                            'config' => iterator_to_array(
                                $this->configMapper->serializeValues(
                                    $blockCreateStruct->getConfigStructs(),
                                    $blockDefinition->getConfigDefinitions()
                                )
                            ),
                        ]
                    ),
                    $persistenceLayout,
                    $targetBlock,
                    $placeholder
                );

                $collectionCreateStructs = $blockCreateStruct->getCollectionCreateStructs();
                if (count($collectionCreateStructs) > 0) {
                    foreach ($collectionCreateStructs as $identifier => $collectionCreateStruct) {
                        $createdCollection = $this->collectionHandler->createCollection(
                            CollectionCreateStruct::fromArray(
                                [
                                    'status' => Value::STATUS_DRAFT,
                                    'offset' => $collectionCreateStruct->offset,
                                    'limit' => $collectionCreateStruct->limit,
                                    'alwaysAvailable' => $blockCreateStruct->alwaysAvailable,
                                    'isTranslatable' => $blockCreateStruct->isTranslatable,
                                    'mainLocale' => $persistenceLayout->mainLocale,
                                ]
                            )
                        );

                        if ($collectionCreateStruct->queryCreateStruct instanceof APIQueryCreateStruct) {
                            $queryType = $collectionCreateStruct->queryCreateStruct->getQueryType();
                            $this->collectionHandler->createQuery(
                                $createdCollection,
                                QueryCreateStruct::fromArray(
                                    [
                                        'type' => $queryType->getType(),
                                        'parameters' => iterator_to_array(
                                            $this->parameterMapper->serializeValues(
                                                $queryType,
                                                $collectionCreateStruct->queryCreateStruct->getParameterValues()
                                            )
                                        ),
                                    ]
                                )
                            );
                        }

                        if ($blockCreateStruct->isTranslatable) {
                            foreach ($persistenceLayout->availableLocales as $locale) {
                                if ($locale !== $persistenceLayout->mainLocale) {
                                    $createdCollection = $this->collectionHandler->createCollectionTranslation(
                                        $createdCollection,
                                        $locale,
                                        $createdCollection->mainLocale
                                    );
                                }
                            }
                        }

                        $this->blockHandler->createCollectionReference(
                            $createdBlock,
                            $createdCollection,
                            (string) $identifier
                        );
                    }
                }

                return $createdBlock;
            }
        );

        return $this->mapper->mapBlock($createdBlock);
    }
55789
public function setOwner(HTML_QuickForm2_Node $owner)
    {
        if (null !== $this->owner) {
            $this->owner->removeRule($this);
        }
        $this->owner = $owner;
    }
8644
public function add($owner, $sample, $size = 1, $type = 'default')
    {
        $size = MANAPHP_COROUTINE ? $size : 1;

        $owner_id = spl_object_id($owner);

        if (!isset($this->_pool[$owner_id][$type])) {
            $this->_pool[$owner_id][$type] = $queue = new \SplQueue();
        } else {
            $queue = $this->_pool[$owner_id][$type];
        }

        if (is_array($sample)) {
            $class = $sample['class'];
            unset($sample['class']);
            $sample = $this->_di->getInstance($class, $sample);
        }

        $queue->push(clone $sample);

        for ($i = 1; $i < $size; $i++) {
            $queue->push(clone $sample);
        }

        return $this;
    }
692378
public function setOwner($type, $id)
    {
        $this->ownerType = $type;
        $this->ownerId = $id;

        $this->server->getEventEmitter()->emit(new SessionOwnerEvent($this));

        return $this;
    }
107258
private function resolveType(BlockTypeInterface $type)
    {
        $typeExtensions = [];
        $parentType = $type->getParent();
        $fqcn = \get_class($type);

        foreach ($this->extensions as $extension) {
            $typeExtensions = array_merge(
                $typeExtensions,
                $extension->getTypeExtensions($fqcn)
            );
        }

        return $this->resolvedTypeFactory->createResolvedType(
            $type,
            $typeExtensions,
            $parentType ? $this->getType($parentType) : null
        );
    }
1278258
public function setOwner(\WobbleCode\UserBundle\Document\User $owner)
    {
        $this->owner = $owner;
        return $this;
    }
685431
protected function reorder($parentId = 0)
    {
        $query = call_user_func("$this->ownerClassName::find")
            ->select("$this->primaryKey")
            ->orderBy("$this->sortField, $this->primaryKey");
        if ( $this->parentIdField ) {
            $query->where([ $this->parentIdField => $parentId ]);
        }
        $data = array_map('intval', $query->column());
        foreach ( $data as $i => $itemPK ) {
            call_user_func("$this->ownerClassName::updateAll",
                [ $this->sortField => ($i + 1) * 100 ],
                [ $this->primaryKey => $itemPK ]);
        }
    }
855179
public function create($rowOrName, $type = null, array $data = [])
    {
        // Check if row or name is defined
        if (!(
            $rowOrName instanceof Model\RowInterface ||
            (is_string($rowOrName) && 0 < strlen($rowOrName))
        )
        ) {
            throw new InvalidOperationException("Excepted instance of RowInterface or string.");
        }

        // Default type if null
        if (null === $type) {
            $type = $this->defaultType;
        }

        // New instance
        $block = $this->editor->getRepository()->createBlock();
        $block->setType($type);

        // Layout creation
//        $this->editor->getLayoutAdapter()->createBlock($block, $data);

        // Plugin creation
        $this->editor->getBlockPlugin($type)->create($block, $data);

        // Add to row if available
        if ($rowOrName instanceof Model\RowInterface) {
            $count = $rowOrName->getBlocks()->count();
            $block
                ->setPosition($count);

            $rowOrName->addBlock($block);
        } else {
            $block->setName($rowOrName);
        }

        return $block;
    }