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/Eurotools/euro-tools.nl/app/KommaApp/Users/Kms/UserService.php
<?php
/**
 * Created by PhpStorm.
 * User: julesgraus
 * Date: 31/01/2018
 * Time: 13:13
 */

namespace App\KommaApp\Users\Kms;

use App\KommaApp\Kms\Core\Attributes\Attribute;
use App\KommaApp\Kms\Core\Attributes\Models\SelectOption;
use App\KommaApp\Kms\Core\Attributes\Password;
use App\KommaApp\Kms\Core\Sections\SectionService;
use App\KommaApp\Kms\Core\Sections\SectionTabItem;
use App\KommaApp\Kms\Core\Tree\Tree;
use App\KommaApp\Kms\Core\Tree\TreeNode;
use App\KommaApp\Kms\SidebarListItem;
use App\KommaApp\Users\Models\Role;
use App\KommaApp\Users\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\Request;

class UserService extends SectionService
{
    use SendsPasswordResetEmails;

    protected $sortable = false;

    function __construct()
    {
        $this->forModelName = User::class;

        parent::__construct();
    }

    /**
     * This method will get all the models.
     * And add these to the sidebarList.
     *
     * @return array $sidebarList
     */
    public function getModelsForSideBar():array
    {
        // Get users based upon your user role
        if (\Auth::user()->role->id <= Role::Admin) {
            $users = User::all();
        }
        elseif (\Auth::user()->role->id >= Role::Editor) {
            $users = User::where('role_id', '>', Role::Admin)->orWhere('id', \Auth::user()->id)->get();
        }
        else {
            $users = User::where('id', '=', \Auth::user()->id)->get();
        }


        $sidebarList = [];
        foreach ($users as $user) {
            //New SidebarListItem
            $sidebarListItem = new SidebarListItem();
            $user->title = $user->username; //used in KmsRepository::setThumbnail
            $this->setThumbnail($user);
            $this->generateThumbnail($user);

            //Set the values for the sidebar
            $sidebarListItem->setId($user->id);
            $sidebarListItem->setStatus(!$user->is_admin);
            $sidebarListItem->setName($user->username);
            $sidebarListItem->setThumbnail($user->thumbnail);

            $sidebarList[] = $sidebarListItem;
        }

        return $sidebarList;
    }

    /**
     * This method will save an model
     *
     * @param Model $model or null
     * @param Collection $sectionTabItems These must be filled with data. This is something you need to do yourself.
     *
     * @return mixed
     */
    public function saveModel(Model $model = null, Collection $sectionTabItems): Model
    {
        /** @var User $model */
        $editedModel = false;
        $sendApprovedMail = false;

        $sectionTabItems->each(
            function($sectionTabItem, $key) use($model, &$editedModel, &$sendApprovedMail) {
                /** @var User $model */
                /** @var SectionTabItem $sectionTabItem */
                $attribute = $sectionTabItem->getAttribute();

//              if(is_a($attribute, Select::class)) dd($attribute); //debugging helper

                $reference = $attribute->getsValueFromReference();
                switch ($attribute->getsValueFrom()) {
                    case Attribute::ValueFromModel:
                        if($reference === 'role_id') {
                            $roleId = $attribute->getValue();
                            $model->role_id = $roleId;
                            $editedModel = true;
                        } else if($reference === 'approved') {
                            $currentApproveStatus = $model->approved;
                            if($currentApproveStatus == 0 && $attribute->getValue() == 1)
                            {
                                $sendApprovedMail = true;
                                $model->approved_at = null;
                            }
                            $editedModel = true;
                        } elseif ($reference == 'password') {
                            /** @var Password $attribute */
                            if($attribute->isEmpty()) {
                                //Prevents the parent from saving an empty password hash since "valueFromItself" isn't save to the database at all
                                $attribute->mapValueFrom(Attribute::ValueFromItself, '');
                            }
                        }
                        break;
                }
            }
        );

        if($editedModel) $model->save();

        $model = parent::saveModel($model, $sectionTabItems);

        if($sendApprovedMail) {
            $this->sendResetLinkEmail(new Request(['email' => $model->email])); //Also see user's sendPasswordResetNotification method
        }

        return $model;
    }

    /**
     * @param int|null $siteId
     * @param int|null $languageId    TODO: Jules. Check if we still need this
     * @param int|null $excludeId     TODO: Jules. Check if we still need this
     * @return SelectOptionInterface[]
     */
    public function getOptionsForSelect($languageId = null, int $excludeId = null): array
    {
        $entities = [];

        // Check if the getModelsAsTree method exist
//        if ( ! method_exists($this, 'getModelsAsTree')) {
        if ( $this->sortable == false) {
            /** @var $sidebarListItems SidebarListItem[] */
            $sidebarListItems = $this->getModelsForSideBar();

            if ($excludeId == -1) $entities = [];
            foreach ($sidebarListItems as $sidebarListItem) {
                $model = $this->forModelName::find($sidebarListItem->getId());
                if(!$model) continue;

                $entities[] = (new SelectOption())
                    ->setValue($model->id)
                    ->setContent($sidebarListItem->getName())
                    ->setHtmlContent($sidebarListItem->getName());
            }
            return $entities;
        }

        // Get all models as tree
        /** @var Tree $tree */
        $tree = $this->getModelsAsTree($languageId);

        // Exclude the current active item)
        if ($excludeId) $tree->removeFromIndex((int)$excludeId);

        // QnD !!! Indexing trees per language (multiple queries)
        $treePerLanguage = [];

        $siteLanguages = $this->kms->getSiteLanguages();

        foreach ($siteLanguages as $language) {
            $treePerLanguage[$language->id] = $this->getModelsAsTree($language->id);
        }
        // End QnD !!!

        // The tree index contains all nodes keyed by id
        /** @var TreeNode $record */
        foreach ($tree->getIndex() as $record) {
            $nodeName = null;

            $sidebarListItem = $record->node;

            $entity = (new SelectOption())->setValue($sidebarListItem->id);

            // For each site language
            foreach ($siteLanguages as $language) {
//                Route with lanuage: Get the primary route for the current language

                /** @var Tree $currentTree */
                $currentTree = $treePerLanguage[$language->id];

                //If $nodeName exist, continue
                if ($nodeName) continue;

                //No nodeName, get one
                /** @var Tree[] $treePerLanguage*/
//                $nodeName = $treePerLanguage[$language->id]->getEntityById($entity['value'])->getTranslationField('name', $language);
                $nodeName = $treePerLanguage[$language->id]->getEntityById($entity->getValue())->getTranslationField('name', $language);
            }

            $entity->setContent((empty($nodeName) ? '/' : $nodeName));

            //Set the spaces for an indent (three)
            $indent = str_repeat('&nbsp;&nbsp;&nbsp;', $record->getDepth());

            //Set the content for the dropdown list
            $entity->setHtmlContent($indent . (empty($nodeName) ? '/' : ucfirst($nodeName) ));

            $entities[] = $entity;
        }
        return $entities;
    }

    /**
     * For the sendResetLink email call above. We know the email is valid at this point so we always return true
     *
     * @param  \Illuminate\Http\Request $request
     * @return bool
     */
    protected function validateEmail(Request $request)
    {
        return true;
    }
}