@internal

@param Content   $entity
@param Bag       $contentType
@param int       $length
@param Parsedown $markdown

@return string
338250
public static function createFromEntity(Content $entity, Bag $contentType, $length, Parsedown $markdown)
    {
        $parts = new MutableBag();

        foreach ($contentType->get('fields', []) as $key => $field) {
            // Skip empty fields, and fields used as 'title'.
            $fieldValue = $entity->get($key);
            if (!$fieldValue || $fieldValue === $entity->getTitle()) {
                continue;
            }
            // Add 'text', 'html' and 'textarea' fields.
            if (in_array($field['type'], ['text', 'html', 'textarea'])) {
                $parts[] = $fieldValue;
            }
            // Add 'markdown' field
            if ($field['type'] === 'markdown') {
                $parts[] = $markdown->text($fieldValue);
            }
        }
        $excerpt = new static($parts->join(' '), $entity->getTitle());

        return $excerpt->getExcerpt($length, true, false);
    }
1288120
public function typeAction($contentDocument, $_format, Request $request)
    {
        if (!$contentDocument || ! $contentDocument instanceof Page) {
            throw new NotFoundHttpException('Content not found');
        }
        if ($this->container->has('profiler')) {
        	$this->container->get('profiler')->disable();
        }
        $isAdminUi = $request->query->get('admin', false) && $this->container->get('security.context')->isGranted('ROLE_ADMIN');

        $data = $params = $this->formatter->format($contentDocument);
		if("html" == $_format) {
	        $params = array(
	            'cmfMainContent' => $contentDocument,
	        	'jsData' => $data,
	        	'settings' => array("currentPath"=>"/","urlBase"=>"/"),
	        	'isAdminUI' => $isAdminUi,
	        	'serializationContext' => $this->getSerializerContext(array('front'))
	        );
		}

        return $this->renderResponse('ApplicationToguApplicationModelsBundle:Default:index.html.twig', $params);
    }
1277073
private function prepareFields(ApiContentType $contentType, $fields = null)
    {
        if ($fields !== null) {
            if (strpos($fields, ',') !== false) {
                return explode(',', $fields);
            }

            return array($fields);
        }

        $fields = array();
        $contentFields = $contentType->getFieldDefinitions();

        foreach ($contentFields as $field) {
            $fields[] = $field->identifier;
        }

        return $fields;
    }
973181
protected function prepareContentByContentTypeIds($contentTypeIds, Request $request)
    {
        $options = $this->parseParameters($request->query, ['page_size', 'page', 'path', 'hidden', 'lang', 'sa', 'image']);

        $pageSize = (int)$options->get('page_size', self::PAGE_SIZE);
        $page = (int)$options->get('page', 1);
        $offset = $page * $pageSize - $pageSize;
        $path = $options->get('path');
        $hidden = $options->get('hidden');
        $lang = $options->get('lang');
        $siteAccess = $options->get('sa');

        $rootLocationPathString = $this->locationService->loadLocation(
            $this->siteAccessHelper->getRootLocationBySiteAccessName($siteAccess)
        )->pathString;

        $contentItems = array();

        foreach ($contentTypeIds as $contentTypeId) {
            $criteria = array(new Criterion\ContentTypeId($contentTypeId));

            if ($path) {
                $criteria[] = new Criterion\Subtree($path);
            }

            if (!$hidden) {
                $criteria[] = new Criterion\Visibility(Criterion\Visibility::VISIBLE);
            }

            $criteria[] = new Criterion\Subtree($rootLocationPathString);

            $query = new Query();
            $query->query = new Criterion\LogicalAnd($criteria);
            $query->limit = $pageSize;
            $query->offset = $offset;

            $contentItems[$contentTypeId] = $this->searchService->findContent(
                $query,
                (!empty($lang) ? array('languages' => array($lang)) : array())
            )->searchHits;
        }

        $contentOptions = $this->parseParameters($request->query, ['lang', 'fields', 'image']);

        return $this->content->prepareContent($contentItems, $contentOptions);
    }
275002
private function setPostedValues(Entity\Content $content, $formValues, $contentType)
    {
        // Ensure all fields have valid values
        $formValues = $this->setSuccessfulControlValues($formValues, $contentType['fields']);
        $formValues = Input::cleanPostedData($formValues);
        unset($formValues['contenttype']);

        $user = $this->users->getCurrentUser();
        if ($id = $content->getId()) {
            // Owner is set explicitly, is current user is allowed to do this?
            if (isset($formValues['ownerid']) && (int) $formValues['ownerid'] !== $content->getOwnerid()) {
                if (!$this->users->isAllowed("contenttype:{$contentType['slug']}:change-ownership:$id")) {
                    throw new AccessControlException('Changing ownership is not allowed.');
                }
                $content->setOwnerid($formValues['ownerid']);
            }
        } else {
            $content->setOwnerid($user['id']);
        }

        // Hack … remove soon
        $formValues += ['status' => 'draft'];
        // Make sure we have a proper status.
        if (!in_array($formValues['status'], ['published', 'timed', 'held', 'draft'])) {
            if ($status = $content->getStatus()) {
                $formValues['status'] = $status;
            } else {
                $formValues['status'] = 'draft';
            }
        }

        // Set the object values appropriately
        foreach ($formValues as $name => $value) {
            if ($name === 'relation' || $name === 'taxonomy') {
                continue;
            }
            $content->set($name, (empty($value) || $this->isEmptyArray($value)) ? null : $value);
        }
        foreach ($contentType['fields'] as $fieldName => $data) {
            if ($data['type'] !== 'slug' || !isset($formValues[$fieldName])) {
                continue;
            }
            if ($this->slugify !== null) {
                $snail = $this->slugify->slugify($formValues[$fieldName]);
            } else {
                // @deprecated Required for BC overrides
                $snail = Slugify::create()->slugify($formValues[$fieldName]);
            }
            $content->set($fieldName, $snail);
        }

        $this->setPostedRelations($content, $formValues);
        $this->setPostedTaxonomies($content, $formValues);
    }
1369742
protected function parseContentType($key, $contentType, $generalConfig)
    {
        // If the slug isn't set, and the 'key' isn't numeric, use that as the slug.
        if (!isset($contentType['slug']) && !is_numeric($key)) {
            $contentType['slug'] = Slugify::create()->slugify($key);
        }

        // If neither 'name' nor 'slug' is set, we need to warn the user. Same goes for when
        // neither 'singular_name' nor 'singular_slug' is set.
        if (!isset($contentType['name']) && !isset($contentType['slug'])) {
            $error = sprintf("In contenttype <code>%s</code>, neither 'name' nor 'slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
            throw new InvalidArgumentException($error);
        }
        if (!isset($contentType['singular_name']) && !isset($contentType['singular_slug'])) {
            $error = sprintf("In contenttype <code>%s</code>, neither 'singular_name' nor 'singular_slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
            throw new InvalidArgumentException($error);
        }

        // Contenttypes without fields make no sense.
        if (!isset($contentType['fields'])) {
            $error = sprintf("In contenttype <code>%s</code>, no 'fields' are set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
            throw new InvalidArgumentException($error);
        }

        if (!isset($contentType['slug'])) {
            $contentType['slug'] = Slugify::create()->slugify($contentType['name']);
        }
        if (!isset($contentType['name'])) {
            $contentType['name'] = ucwords(preg_replace('/[^a-z0-9]/i', ' ', $contentType['slug']));
        }
        if (!isset($contentType['singular_slug'])) {
            $contentType['singular_slug'] = Slugify::create()->slugify($contentType['singular_name']);
        }
        if (!isset($contentType['singular_name'])) {
            $contentType['singular_name'] = ucwords(preg_replace('/[^a-z0-9]/i', ' ', $contentType['singular_slug']));
        }
        if (!isset($contentType['show_on_dashboard'])) {
            $contentType['show_on_dashboard'] = true;
        }
        if (!isset($contentType['show_in_menu'])) {
            $contentType['show_in_menu'] = true;
        }
        if (!isset($contentType['sort'])) {
            $contentType['sort'] = false;
        }
        if (!isset($contentType['default_status'])) {
            $contentType['default_status'] = 'draft';
        }
        if (!isset($contentType['viewless'])) {
            $contentType['viewless'] = false;
        }
        if (!isset($contentType['liveeditor'])) {
            $contentType['liveeditor'] = true;
        }
        // Override contenttype setting with view and config settings
        if (($contentType['viewless']) || (!$generalConfig['liveeditor'])) {
            $contentType['liveeditor'] = false;
        }
        // Allow explicit setting of a Contenttype's table name suffix. We default
        // to slug if not present as it has been this way since Bolt v1.2.1
        if (!isset($contentType['tablename'])) {
            $contentType['tablename'] = Slugify::create()->slugify($contentType['slug'], '_');
        } else {
            $contentType['tablename'] = Slugify::create()->slugify($contentType['tablename'], '_');
        }
        if (!isset($contentType['allow_numeric_slugs'])) {
            $contentType['allow_numeric_slugs'] = false;
        }
        if (!isset($contentType['singleton'])) {
            $contentType['singleton'] = false;
        }

        list($fields, $groups) = $this->parseFieldsAndGroups($contentType['fields'], $generalConfig);
        $contentType['fields'] = $fields;
        $contentType['groups'] = $groups;

        // Make sure taxonomy is an array.
        if (isset($contentType['taxonomy'])) {
            $contentType['taxonomy'] = (array) $contentType['taxonomy'];
        }

        // when adding relations, make sure they're added by their slug. Not their 'name' or 'singular name'.
        if (!empty($contentType['relations']) && is_array($contentType['relations'])) {
            foreach (array_keys($contentType['relations']) as $relkey) {
                if ($relkey != Slugify::create()->slugify($relkey)) {
                    $contentType['relations'][Slugify::create()->slugify($relkey)] = $contentType['relations'][$relkey];
                    unset($contentType['relations'][$relkey]);
                }
            }
        }

        return $contentType;
    }
1234871
public function withContentType($contentType, $charset = null)
    {
        if (is_null($charset)) {
            return $this->withHeader('Content-Type', $contentType);
        }

        return $this->withHeader('Content-Type', $contentType . '; charset=' . $charset);
    }
932500
public function getChangeLogByContentTypeQuery($contentType, array $options)
    {
        $alias = $this->getAlias();
        $contentTableName = $this->em->getRepository($contentType)->getTableName();

        $qb = $this->createQueryBuilder();
        $qb->select("$alias.*, $alias.title")
            ->leftJoin($alias, $contentTableName, 'content', "content.id = $alias.contentid");

        // Set required WHERE
        $this->setWhere($qb, $contentType, $options);

        // Set ORDER BY and LIMIT as requested
        $this->setLimitOrder($qb, $options);

        return $qb;
    }
511426
private function selectContentTypeHeader($contentType)
    {
        if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) {
            return 'application/json';
        } elseif (preg_grep("/application\/json/i", $contentType)) {
            return 'application/json';
        } else {
            return implode(',', $contentType);
        }
    }
337938
protected static function createDocumentWrapper($html, $contentType = null, $documentID = null) 
    {
        if (function_exists('domxml_open_mem')) {
            throw new Exception("Old PHP4 DOM XML extension detected. phpQuery won't work until this extension is enabled.");
        }
        //        $id = $documentID
        //            ? $documentID
        //            : md5(microtime());
        $document = null;
        if ($html instanceof DOMDOCUMENT) {
            if (self::getDocumentID($html)) {
                // document already exists in phpQuery::$documents, make a copy
                $document = clone $html;
            } else {
                // new document, add it to phpQuery::$documents
                $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
            }
        } else {
            $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
        }
        //        $wrapper->id = $id;
        // bind document
        phpQuery::$documents[$wrapper->id] = $wrapper;
        // remember last loaded document
        phpQuery::selectDocument($wrapper->id);
        return $wrapper->id;
    }
1091876
private function resolveContentEditData(
        Content $content,
        string $languageCode,
        ContentType $contentType
    ): ContentUpdateData {
        $contentUpdateMapper = new ContentUpdateMapper();

        return $contentUpdateMapper->mapToFormData($content, [
            'languageCode' => $languageCode,
            'contentType' => $contentType,
        ]);
    }
933210
public function getContent(string $contentType = null): string
    {
/*
        if(null == $contentType)
            $contentType = $this->contentType;
*/
        switch($contentType) {
            case 'application/vnd.transitive.document+json':
                return $this->route->getDocument();
            break;
            case 'application/vnd.transitive.document+xml':
                return $this->route->getDocument()->asXML('document');
            break;
            case 'application/vnd.transitive.document+yaml':
                return $this->route->getDocument()->asYAML();
            break;
            case 'application/vnd.transitive.head+json':
                return $this->route->getHead()->asJson();
            break;
            case 'application/vnd.transitive.head+xml':
                return $this->route->getHead()->asXML('head');
            break;
            case 'application/vnd.transitive.head+yaml':
                return $this->route->getHead()->asYAML();
            break;
            case 'application/vnd.transitive.content+xhtml': case 'application/vnd.transitive.content+html':
                return $this->route->getContent();
            break;
            case 'application/vnd.transitive.content+json':
                return $this->route->getContent()->asJson();
            break;
            case 'application/vnd.transitive.content+xml':
                return $this->route->getContent()->asXML('content');
            break;
            case 'application/vnd.transitive.content+yaml':
                return $this->route->getContent()->asYAML();
            break;

            case 'text/plain':
                return $this->layout->getContent()->asString();
            break;

            case 'application/json':
                if($this->route->hasContent('application/json'))
                    return $this->route->getContentByType('application/json')->asJson();
                elseif(404 != http_response_code()) {
                    http_response_code(404);
                    $_SERVER['REDIRECT_STATUS'] = 404;

                    return '';
                }
            break;
            case 'application/xml':
                if($this->route->hasContent('application/xml'))
                    return $this->route->getContentByType('application/xml')->asJson();
                elseif(404 != http_response_code()) {
                    http_response_code(404);
                    $_SERVER['REDIRECT_STATUS'] = 404;

                    return '';
                }

            break;

            default:
                return $this->layout->getView();
        }
    }
543502
protected function GetBoundary($boundary, $charSet, $contentType, $encoding)
    {
        $result = '';
        if ($charSet == '') {
            $charSet = $this->CharSet;
        }
        if ($contentType == '') {
            $contentType = $this->ContentType;
        }
        if ($encoding == '') {
            $encoding = $this->Encoding;
        }
        $result .= $this->TextLine('--' . $boundary);
        $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
        $result .= $this->LE;
        $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
        $result .= $this->LE;

        return $result;
    }
610483
public void setContentType(String contentType) 
    {
        if (isCommitted())
            return;
        
        if (contentType==null)
        {
            _mimeType=null;
            _header.remove(HttpFields.__ContentType);
        }
        else
        {
            // Look for encoding in contentType
            int i0=contentType.indexOf(';');
            
            if (i0>0)
            {
                // Strip params off mimetype
                _mimeType=contentType.substring(0,i0).trim();
                
                // Look for charset
                int i1=contentType.indexOf("charset=",i0);
                if (i1>=0)
                {
                    i1+=8;
                    int i2 = contentType.indexOf(' ',i1);
                    _characterEncoding = (0<i2)
                    ? contentType.substring(i1,i2)
                                    : contentType.substring(i1);
                    _characterEncoding = QuotedStringTokenizer.unquote(_characterEncoding);
                }
                else // No encoding in the params.
                {
                    if (_characterEncoding!=null)
                        // Add any previously set encoding.
                        contentType+=";charset="+QuotedStringTokenizer.quote(_characterEncoding,";= ");
                }
            }
            else // No encoding and no other params
            {
                _mimeType=contentType;
                // Add any previously set encoding.
                if (_characterEncoding!=null)
                    contentType+=";charset="+QuotedStringTokenizer.quote(_characterEncoding,";= ");
            }
            
            _header.put(HttpFields.__ContentType,contentType);
        }
    }
636377
public function setContentType($contentType, $charset=NULL){
        $this->setHeader("Content-Type", $contentType);
        if($charset != NULL){
            $this->setHeader("charset", $charset);
        }
    }
1126909
protected function getBoundary($boundary, $charSet, $contentType, $encoding)
    {
        $result = '';
        if ('' == $charSet) {
            $charSet = $this->CharSet;
        }
        if ('' == $contentType) {
            $contentType = $this->ContentType;
        }
        if ('' == $encoding) {
            $encoding = $this->Encoding;
        }
        $result .= $this->textLine('--' . $boundary);
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
        $result .= static::$LE;
        // RFC1341 part 5 says 7bit is assumed if not specified
        if ('7bit' != $encoding) {
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
        }
        $result .= static::$LE;

        return $result;
    }
839019
private function doGetCollectionByContent($contentType, $contentUid)
    {
        $content = null;
        $classname = AbstractClassContent::getClassnameByContentType($contentType);
        $em = $this->getApplication()->getEntityManager();

        try {
            $content = $em->find($classname, $contentUid);
        } catch (ClassNotFoundException $e) {
            throw new NotFoundHttpException("No classcontent found with provided type (:$contentType)");
        }

        if (null === $content) {
            throw new NotFoundHttpException("No `$classname` exists with uid `$contentUid`");
        }

        $pages = $em->getRepository("BackBee\ClassContent\AbstractClassContent")->findPagesByContent($content);

        $response = $this->createResponse($this->formatCollection($pages));
        if (0 < count($pages)) {
            $response->headers->set('Content-Range', '0-'.(count($pages) - 1).'/'.count($pages));
        }

        return $response;
    }