File Hydration.

@param Model $model
@param \Tapestry\Entities\File $file
@param \TapestryCloud\Database\Entities\ContentType $contentType
480065
public function hydrate(Model $model, \Tapestry\Entities\File $file, \TapestryCloud\Database\Entities\ContentType $contentType = null)
    {
        $model->setUid($file->getUid());
        $model->setLastModified($file->getLastModified());
        $model->setFilename($file->getFilename());
        $model->setExt($file->getExt());
        $model->setPath($file->getPath());
        $model->setToCopy($file->isToCopy());
        $model->setDate($file->getData('date')->getTimestamp());
        $model->setIsDraft($file->getData('draft', false));

        if (!$file->isToCopy()) {
            $frontMatter = new TapestryFrontMatter($file->getFileContent());
            $model->setContent($frontMatter->getContent());

            $inFile = [];
            foreach (array_keys($frontMatter->getData()) as $inFileKey) {
                $inFile[$inFileKey] = 1;
            }

            $inDatabase = [];
            foreach ($model->getFrontMatterKeys() as $inDatabaseKey) {
                if (isset($inFile[$inDatabaseKey])) {
                    $inDatabase[$inDatabaseKey] = 1;
                } else {
                    $inDatabase[$inDatabaseKey] = -1; //@todo remove frontmatter from db when missing from file
                }
            }

            foreach ($frontMatter->getData() as $key => $value) {
                $fmRecord = new FrontMatter();
                $fmRecord->setName($key);

                if (isset($inDatabase[$key])){
                    $fmRecord = $model->getFrontMatterByKey($key, $fmRecord);
                }

                $fmRecord->setValue(json_encode($value));
                $model->addFrontMatter($fmRecord);

                $this->entityManager->persist($fmRecord);
            }
        }

        if (!is_null($contentType)) {
            $model->setContentType($contentType);
        }
    }
480481
public function loadDatabase(string $file): void
	{
		$this->connection->transactional(function (Connection $db) use ($file) {
			$db->query('SET foreign_key_checks = 0');
			FileImporter::executeFile($db, $file);
			$db->query('SET foreign_key_checks = 1');
		});
	}
877112
public static function serve($filename, $contentType, $options)
    {
        $options = array_merge(self::$defaultOptions, $options);

        if ($options['set-last-modified-header'] === true) {
            Header::setHeader("Last-Modified: " . gmdate("D, d M Y H:i:s", @filemtime($filename)) ." GMT");
        }

        if ($options['set-content-type-header'] === true) {
            Header::setHeader('Content-type: ' . $contentType);
        }

        if ($options['add-vary-accept-header'] === true) {
            Header::addHeader('Vary: Accept');
        }

        if ($options['set-cache-control-header'] === true) {
            if (!empty($options['cache-control-header'])) {
                Header::setHeader('Cache-Control: ' . $options['cache-control-header']);

                // Add exprires header too (#126)
                // Check string for something like this: max-age:86400
                if (preg_match('#max-age\\s*=\\s*(\\d*)#', $options['cache-control-header'], $matches)) {
                    $seconds = $matches[1];
                    Header::setHeader('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + intval($seconds)));
                }
            }
        }

        if (@readfile($filename) === false) {
            Header::addHeader('X-WebP-Convert-Error: Could not read file');
            throw new ServeFailedException('Could not read file');
        }
    }
125399
public function setContentType(string $contentType): void
    {
        $this->contentType = $contentType;
        // TODO: This can be removed after the full changes are done for next major.
        $this->headers->set('Content-Type', $contentType, true);
    }
83059
public function addEmbeddedFile(string $file, string $content = null, string $contentType = null): MimePart
    {
        return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
            ->setHeader('Content-ID', $this->getRandomId());
    }
392286
public function addAttachment(string $file, string $content = null, string $contentType = null): self
	{
		$this->message->addAttachment($file, $content, $contentType);
		return $this;
	}
914338
public static function setContentType($contentType, $encoding = null) {
		$value = $contentType;
		if (isset ( $encoding ))
			$value .= ' ;charset=' . $encoding;
		self::header ( 'Content-Type', $value );
	}
273274
public void addFile(String path, File file, String contentType) throws IOException {
    try (InputStream is = new FileInputStream(file)) {
      addFile(path, is, contentType);
    }
  }
765297
private function putContent($file, $content)
    {
        $this->ensureExists(dirname($file));
        touch($file);

        return file_put_contents($file, serialize($content));
    }
668271
public function setFileBody(string $fileBody, string $contentType='')
  {
    # Clear the normal body
    $this->setBody('');

    # Set content type
    if (!empty($contentType)) {
      $this->setContentType($contentType);
    }

    # Set the filename
    $this->fileBody = $fileBody;

    return $this;
  }
1173784
public function sendFile($file, $name=NULL, $contentType='application/octet-stream', $contentDisposition='attachment'){
        if($name == NULL){
            $name= basename($file);
        }
        header('Content-Description: File Transfer');
        header('Content-Type: '.$contentType);
        header('Content-Disposition: '.$contentDisposition.'; filename="'.$name.'"');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);        
    }
1133950
public function setContentType(string $content_type)
    {
        if (empty($content_type)) {
            Throw new HeaderException('Empty content type is not allowed.');
        }

        $this->content_type = $content_type;
    }
1194646
public function deleteContent($contenttype, $id)
    {
        if (empty($contenttype)) {
            $this->app['logger.system']->error('Contenttype is required for' . __FUNCTION__, ['event' => 'exception']);
            throw new StorageException('Contenttype is required for ' . __FUNCTION__);
        }

        // Make sure $contenttype is a 'slug'
        if (is_array($contenttype)) {
            $contenttype = $contenttype['slug'];
        }

        // Get the old content record
        $tablename = $this->getContenttypeTablename($contenttype);
        $oldContent = $this->findContent($tablename, $id);

        // Dispatch pre-delete event
        if ($this->app['dispatcher']->hasListeners(StorageEvents::PRE_DELETE)) {
            $event = new StorageEvent($oldContent, ['contenttype' => $contenttype]);
            $this->app['dispatcher']->dispatch(StorageEvents::PRE_DELETE, $event);
        }

        $this->logDelete($contenttype, $id, $oldContent);

        $res = $this->app['db']->delete($tablename, ['id' => $id]);

        // Make sure relations and taxonomies are deleted as well.
        if ($res) {
            $this->app['db']->delete($this->getTablename('relations'), ['from_contenttype' => $contenttype, 'from_id' => $id]);
            $this->app['db']->delete($this->getTablename('relations'), ['to_contenttype' => $contenttype, 'to_id' => $id]);
            $this->app['db']->delete($this->getTablename('taxonomy'), ['contenttype' => $contenttype, 'content_id' => $id]);
        }

        // Dispatch post-delete event
        if ($this->app['dispatcher']->hasListeners(StorageEvents::POST_DELETE)) {
            $event = new StorageEvent($oldContent, ['contenttype' => $contenttype]);
            $this->app['dispatcher']->dispatch(StorageEvents::POST_DELETE, $event);
        }

        return $res;
    }
1192088
protected function updateFile(FileInterface $file, $resource, $mimetype = NULL) {
    $uri = $file->getFileUri();

    $destination = fopen($uri, 'wb');
    if (!$destination) {
      throw new HttpException(500, "File $uri could not be opened to write.");
    }

    $content_length = stream_copy_to_stream($resource, $destination);

    fclose($destination);

    if ($content_length === FALSE) {
      throw new HttpException(500, "Request body could not be copied to $uri");
    }

    if ($content_length === 0) {
      // Clean up the newly created, empty file.
      unlink($uri);
      throw new HttpException(400, "No bytes were copied to $uri");
    }

    if (!empty($mimetype)) {
      $file->setMimeType($mimetype);
    }

    // Flush the image cache for the image so thumbnails get regenerated.
    image_path_flush($uri);
  }
44477
public function optimizeCssContent(AssetCacheManager $assetCacheManager, $content, $file)
    {
        $this->assetCacheManager = $assetCacheManager;
        
        $content = $this->optimizeUrls($content, $file);
        
        return $content;
    }
225818
public static function createFromFile(string $filename, string $contentType = null): self
    {
        $instance = new static();
        $instance->content = \file_get_contents($filename);
        $instance->name = \basename($filename);

        if (null !== $contentType) {
            $instance->contentType = $contentType;
        }

        return $instance;
    }
646097
private function addRecord(MutableBag $contentTypeBag, ClassMetadata $metadata, Content $entity)
    {
        $values = [];
        foreach ($metadata->getFieldMappings() as $field) {
            $fieldName = $field['fieldname'];
            $val = $entity->$fieldName;
            if (in_array($field['type'], ['date', 'datetime'])) {
                $val = (string) $entity->$fieldName;
            }
            if (is_callable([$val, 'serialize'])) {
                /** @var Entity $val */
                $val = $val->serialize();
            }
            $values[$fieldName] = $val;
        }

        unset($values['id']);
        $values['_id'] = $entity->getContentType() . '/' . $entity->getSlug();
        $contentTypeBag->add($values);
    }