HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/stafa/stafa.nl/app/Komma/Kms/Core/Attributes/Models/Traits/HasThumbnailTrait.php
<?php


namespace App\Komma\Kms\Core\Attributes\Models\Traits;

use App\Komma\Documents\Kms\DocumentableInterface;
use App\Komma\Documents\Models\Document;
use App\Komma\Kms\Core\Entities\DisplayNameInterface;
use Illuminate\Database\Eloquent\Model;

/**
 * Trait HasThumbnailTrait
 *
 * Used on eloquent models
 *
 * @package App\Komma\Kms\Core\Attributes\Models\Traits
 */
trait HasThumbnailTrait
{
    /** @var bool|string Transient model property. Holds HTML that represents a thumbnail for the model OR false if it has not have a thumbnail */
    private $thumbnail = false;

    /**
     * Set the thumbnail for the model using different strategies.
     * 1. It tries to use the first uploaded document that is an image.
     * 2. If that is null, it will try to use the path parameter.
     * 3. If that is null, it will use the first letter of the DisplayName of the model
     * 4. As a last resort it will use the models id
     *
     * @param string|null $path
     * @return HasThumbnailTrait|Model
     */
    public function generateThumbnail(string $path = null)
    {
        // 1. Set thumbnail to first uploaded image if there is one
        if(is_a($this, DocumentableInterface::class) && $document = $this->documents->where('mime_type', 'like', 'image/%')->first())
        {
            /** @var Document $document */
            $this->thumbnail = '<img src="' . $document->thumb_image_url. '"/>';        // 2. else use the path if specified
        } elseif($path) {
            if($path) $this->thumbnail = '<img src="' . $path. '"/>';
        // 3. else use the first letter of the DisplayName if there is one
        } elseif(is_a($this,DisplayNameInterface::class) && $displayName = $this->getDisplayName()) {
            $this->thumbnail = '<span>'.strtoupper(substr($displayName, 0, 1)).'</span>';
        // 4. else use the id of the model
        } else {
            $this->thumbnail = '<span>'.strtoupper($this->id).'</span>';
        }

        return $this;
    }

    /**
     * Returns the HTML to display the models
     */
    public function getThumbnail():string
    {
        return $this->thumbnail;
    }
}