<commit_before><?php

namespace CatLab\Assets\Laravel\Controllers;

use CatLab\Assets\Laravel\Models\Asset;

use DateInterval;
use DateTime;
use DateTimeImmutable;
use Request;
use Response;

/**
 * Class AssetController
 * @package CatLab\Assets\Controllers
 */
class AssetController
{
    const QUERY_PARAM_SQUARE = 'square';
    const QUERY_PARAM_WIDTH = 'width';
    const QUERY_PARAM_HEIGHT = 'height';

    /**
     * @param $assetId
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function view($assetId)
    {
        /** @var Asset $asset */
        $asset = Asset::find($assetId);
        if (!$asset) {
            abort(404, 'Asset ' . $assetId . ' not found.');
        }

        if ($asset->isImage()) {
            return $this->getImageResponse($asset);
        }

        // Do some magic here.
        return $this->getStreamResponse($asset, []);
    }

    /**
     * @return array
     */
    protected function getImageSize()
    {
        if (Request::input(self::QUERY_PARAM_SQUARE)) {
            return [
                Request::input(self::QUERY_PARAM_SQUARE),
                Request::input(self::QUERY_PARAM_SQUARE)
            ];
        }

        elseif (
            Request::input(self::QUERY_PARAM_WIDTH) &&
            Request::input(self::QUERY_PARAM_HEIGHT)
        ) {
            return [
                Request::input(self::QUERY_PARAM_WIDTH),
                Request::input(self::QUERY_PARAM_HEIGHT)
            ];
        }

        return [ null, null ];
    }

    /**
     * @param Asset $asset
     * @return \Illuminate\Http\Response
     */
    protected function getImageResponse(Asset $asset)
    {
        $response = \Illuminate\Http\Response::make(
            $asset->getResizedImage(...$this->getImageSize()),
            200,
            array_merge(
                [
                    'Content-type' => $asset->mimetype
                ],
                $this->getCacheHeaders($asset)
            )
        );

        return $response;
    }

    /**
     * @param Asset $asset
     * @return array
     */
    protected function getCacheHeaders(Asset $asset)
    {
        $expireInterval = new DateInterval('P1Y');
        $expireDate = (new DateTime())->add($expireInterval);

        return [
            'Expires' => $expireDate->format('r'),
            'Last-Modified' => $asset->created_at->format('r'),
            'Cache-Control' => 'max-age=' . $this->dateIntervalToSeconds($expireInterval) . ', public'
        ];
    }

    /**
     * @param DateInterval $dateInterval
     * @return int seconds
     */
    protected function dateIntervalToSeconds($dateInterval)
    {
        $reference = new DateTimeImmutable;
        $endTime = $reference->add($dateInterval);

        return $endTime->getTimestamp() - $reference->getTimestamp();
    }

    /**
     * @param Asset $asset<commit_msg>Don't crash if no creation date was set, even though that shouldn't happen.<commit_after><?php

namespace CatLab\Assets\Laravel\Controllers;

use CatLab\Assets\Laravel\Models\Asset;

use DateInterval;
use DateTime;
use DateTimeImmutable;
use Request;
use Response;

/**
 * Class AssetController
 * @package CatLab\Assets\Controllers
 */
class AssetController
{
    const QUERY_PARAM_SQUARE = 'square';
    const QUERY_PARAM_WIDTH = 'width';
    const QUERY_PARAM_HEIGHT = 'height';

    /**
     * @param $assetId
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function view($assetId)
    {
        /** @var Asset $asset */
        $asset = Asset::find($assetId);
        if (!$asset) {
            abort(404, 'Asset ' . $assetId . ' not found.');
        }

        if ($asset->isImage()) {
            return $this->getImageResponse($asset);
        }

        // Do some magic here.
        return $this->getStreamResponse($asset, []);
    }

    /**
     * @return array
     */
    protected function getImageSize()
    {
        if (Request::input(self::QUERY_PARAM_SQUARE)) {
            return [
                Request::input(self::QUERY_PARAM_SQUARE),
                Request::input(self::QUERY_PARAM_SQUARE)
            ];
        }

        elseif (
            Request::input(self::QUERY_PARAM_WIDTH) &&
            Request::input(self::QUERY_PARAM_HEIGHT)
        ) {
            return [
                Request::input(self::QUERY_PARAM_WIDTH),
                Request::input(self::QUERY_PARAM_HEIGHT)
            ];
        }

        return [ null, null ];
    }

    /**
     * @param Asset $asset
     * @return \Illuminate\Http\Response
     */
    protected function getImageResponse(Asset $asset)
    {
        $response = \Illuminate\Http\Response::make(
            $asset->getResizedImage(...$this->getImageSize()),
            200,
            array_merge(
                [
                    'Content-type' => $asset->mimetype
                ],
                $this->getCacheHeaders($asset)
            )
        );

        return $response;
    }

    /**
     * @param Asset $asset
     * @return array
     */
    protected function getCacheHeaders(Asset $asset)
    {
        $expireInterval = new DateInterval('P1Y');
        $expireDate = (new DateTime())->add($expireInterval);

        return [
            'Expires' => $expireDate->format('r'),
            'Last-Modified' => $asset->created_at ? $asset->created_at->format('r') : null,
            'Cache-Control' => 'max-age=' . $this->dateIntervalToSeconds($expireInterval) . ', public'
        ];
    }

    /**
     * @param DateInterval $dateInterval
     * @return int seconds
     */
    protected function dateIntervalToSeconds($dateInterval)
    {
        $reference = new DateTimeImmutable;
        $endTime = $reference->add($dateInterval);

        return $endTime->getTimestamp() - $reference->getTimestamp();
    }

    /**
     * @param Asset $asset
{'fraction_non_alphanumeric': 0.13447806868412104, 'fraction_numerical': 0.0023801428085685142, 'mean_word_length': 1.960744841469552, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 42, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3390000', 'n_tokens_mistral': 1742, 'n_tokens_neox': 1681, 'n_words': 295}