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/SBogers33/bbec.nl/workbench/komma/kms/src/Komma/Kms/Core/Sections/KmsSection.php
<?php
/**
 * Short description for the file.
 *
 * @author      Komma <info@komma.pro>
 * @copyright   (c) 2012-2015, Komma Mediadesign
 */

namespace Komma\Kms\Core\Sections;

use Illuminate\Events\Dispatcher;
use Illuminate\Support\ViewErrorBag;
use Komma\Kms\Core\Kms;
use Komma\Kms\Core\KmsRepository;

abstract class KmsSection
{
    protected $kms;
    protected $repository;

    protected $eventListeners = [];
    protected $entityAttributesData = [];

    protected $tabs;
    protected $attributes = []; // [ attributes... ]
    protected $entity = null;
    protected $entities = null;

    protected $errors = [];

    protected $title = "";
    protected $subTitle = "";
    protected $slug = "";

    public $submitButtonLabel = "Opslaan";
    public $submitRoute = null;

    public $showSave = 'all';
    public $showDelete = 'all';
    public $showCreate = 'all';

    public $listView = 'kms::partials.entities.index';
    public $view = 'kms::partials.entity.index';

    public $showEntity = true;
    public $type;
    public $dynamic_lock = false;

    function __construct(
        Kms $kms,
        KmsRepository $repository,
        KmsSectionTabs $tabs)
    {
        $this->kms = $kms;
        $this->repository = $repository;
        $this->tabs = $tabs;
        $this->submitButtonLabel = \Config::get('kms::'.\Config::get('kms::main.defaultLanguage').'/translations.save');

        $this->initializeEventListeners();

        // $this->loadEntity();
        $this->loadEntities();
    }

    protected function initializeEventListeners()
    {
        foreach($this->eventListeners as $listenerKey => $listenerValue)
        {
            \Event::listen($listenerKey, $listenerValue);
        }
    }

    public function getRepository()
    {
        return $this->repository;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getSubTitle()
    {
        return $this->subTitle;
    }

    public function getSlug(){
        return $this->slug;
    }

    public function getListView(){
        return $this->listView;
    }

    public function getView(){
        return $this->view;
    }

    public function getEntities()
    {
        return $this->entities;
    }

    public function loadEntities()
    {
        return $this->entities = $this->repository->getEntities($this->type);
    }

    public function isCreatingEntity()
    {
        $val = $this->getEntityId();
        return $val ? false : true;
    }

    public function getEntity()
    {
        return $this->entity;
    }

    public function getThumbnail()
    {
        if($this->getEntity() && $this->getEntity()->getThumbnail())
        {
            return $this->getEntity()->getThumbnail();
        }
        return null;
    }

    /*
     * Checks if the section is redirected from a save action
     */
    public function redirectedFromSaveWithSuccess()
    {
        return \Session::has('success');
    }

    public function redirectedFromSaveWithFailure()
    {
        return \Session::has('errors');
    }

    public function loadEntity($id = null)
    {
        $this->entity = $this->repository->getEntity($id);
        $this->parseEntityAttributesData();

        // $this->populateAttributes();
        return $this->entity;
    }

    public function getEntityId()
    {
        if( ! isset($this->entity)) return false;

        return $this->entity->getId();
    }

    public function getEntityTitle()
    {
        if( ! isset($this->entity)) return false;

        return $this->entity->getName();
    }

    public function getTabs()
    {
        return $this->tabs->getTabs();
    }

    public function getAttributes()
    {
        return $this->attributes;
    }

    public function getPagination()
    {
        return \Paginator::make($this->getEntities(),count($this->getEntities()), 5);
    }

    public function render()
    {
        $this->getEntities();

        return \View::make('kms::section.index', [
            'kms' => $this->kms,
            'section' => $this
        ]);
    }

    public function update($id)
    {
        $this->entity->id = $id;
        $this->save();
    }

    public function save()
    {
        //$this->processAttributes();
        $entity = $this->repository->saveEntity($this->entity);

        \Event::fire('kms.entity.saved.' . $this->slug, $this->entity);
        return $entity;
    }

    public function destroy($id)
    {
        $this->loadEntity($id);
        $this->deleteAttributes();
        return $this->repository->destroyEntity($id);
    }

    /*
     * Push data into attributes
     */
    public function setAttributesData(array $data)
    {
        foreach ($data as $key => $value)
        {
            $this->entity->setValue($key, $value);
        }

        $this->populateAttributes();

    }

    public function setErrors(ViewErrorBag $errors = null)
    {
        if($errors) {
            $this->errors = $errors->getMessages();
            foreach ($this->attributes as $attribute)
            {
                if (isset($this->errors[$attribute->key]))
                {
                    $attribute->setErrors($this->errors[$attribute->key]);
                }
            }
        }
    }

    /**
     * Validate attributes
     *
     * @return \Illuminate\Validation\Validator
     */
    public function validateAttributes()
    {
        // Set variables
        $values = $rules = $messages = [];

        // Loop through attributes
        foreach($this->attributes as $attribute)
        {
            // Put the value in the values array (f.e. $values['title'] = "My title")
            $values[$attribute->getKey()] = $attribute->getRawValue();

            // Check for validation on this attribute (Method in the attribute object)
            if ($attribute->getValidation() == null) continue;

            // Put the rules for this attribute in the $rules array
            $rules[$attribute->getKey()] = $attribute->getValidation()['rules'];

            // Add all messages for the rules in the messages $array
            foreach ($attribute->getValidation()['messages'] as $messageKey => $message)
            {
                $messages[$attribute->getKey() . '.' . $messageKey] = $message;
            }
        }

        // Create the \Illuminate\Validation\Validator object
        $validator =  \Validator::make($values, $rules, $messages);

        return $validator;
    }

    /**
     * Create a list with KmsAttribute Objects, based on $this->entityAttributes
     * @return array
     */
    protected function parseEntityAttributesData()
    {

        $this->attributes = [];
        $this->tabs->clearTabs();

        foreach($this->entityAttributesData as $attributeKey => $attribute)
        {
            $forEach = isset($attribute['forEach']) ? $attribute['forEach'] : null;

            // handle attributes specific for an entity state (create/update)
            if(isset($attribute['entityState']))
            {
                if($attribute['entityState'] == 'create' && (! $this->isCreatingEntity())) continue;
                if($attribute['entityState'] == 'update' && ($this->isCreatingEntity())) continue;
            }

            // create attributes
            switch($forEach)
            {
                case "AllLanguages":
                    $this->createAttributeForAllLanguages($attributeKey, $attribute);
                    break;
                default:
                    $this->createAttribute($attributeKey, $attribute);
                    break;
            }
        }

        return $this->attributes;
    }

    /**
     * Create the attribute object and add it to a tab
     *
     * @param $key
     * @param $attributeData
     */
    protected function createAttribute($key, $attributeData)
    {
        // Check if attribute has a value
        $value = isset($this->entity) && isset($this->entity->$key) ? $this->entity->$key : null;

        // Parse options from Section for attribute (f.e. "label", "class", "placeholder")
        $options = isset($attributeData['options']) ? $this->parseOptions($attributeData['options']) : [];

        // If any validation is found in the options, get an array of validation rules.
        if (isset($options['validation'])) $options['validation'] = $this->parseValidation($options['validation']);

        // Create the actual object with all of it's data
        $item = $this->attributes[] = new $attributeData['type']($key, $value, $options, [], null, $this);

        // Set the tab on which the attribute is displayed
        $tab = isset($attributeData['tab']) ? $attributeData['tab'] : \Config::get('kms::'.\Config::get('kms::main.defaultLanguage').'/translations.general');


        // Add the item to the tab
        $this->tabs->addItem($item, $tab);
    }

    protected function createAttributeForAllLanguages($key, $attributeData)
    {
        // Loop through each language
        // Note: these can be found in Komma/Kms/Config/main.php
        foreach($this->kms->getCurrentLanguages() as $language)
        {
            // Check if attribute has a value
            $value = isset($this->entity) && isset($this->entity->$key) ? $this->entity->$key : null;

            // Parse options from Section for attribute (f.e. "label", "class", "placeholder")
            // Note: parseOptions with $language->id
            $options = isset($attributeData['options']) ? $this->parseOptions($attributeData['options'], $language->id) : [];


            // If any validation is found in the options, get an array of validation rules.
            // Note: parseValidation with $language->id
            if (isset($options['validation'])) $options['validation'] = $this->parseValidation($options['validation'],$language->id);

            // Set the tab to the language ISO (f.e. "nl", "en") or default when only one lang available
            if (count($this->kms->getCurrentLanguages()) == 1) {
                $tab = isset($attributeData['tab']) ? $attributeData['tab'] : \Config::get('kms::'.\Config::get('kms::main.defaultLanguage').'/translations.general');
            } else {
                $tab = $language->iso_2;
            }

            // Overwrite language iso if the tab attribute is found
            // This may only happen if we have just one language
            if(isset($attributeData['tab']) && count($this->kms->getCurrentLanguages()) == 1) $tab = $attributeData['tab'];

            // Instead of using the normal key, add the language id
            $currentKey = $key . '_' . $language->id;

            // Create the actual object with all of it's data
            // Note: instead of the usual key we use the with with language id
            $item = $this->attributes[] = new $attributeData['type']($currentKey, $value, $options, [], $language->id, $this);

            // Add the item to the tab
            $this->tabs->addItem($item, $tab);
        }
    }


    /**
     * Set the section attributes by $this->currentEntities
     * @param array/object $data
     */
    public function populateAttributes()
    {
        foreach ($this->attributes as $attribute)
        {
            $key = $attribute->getKey();
            $value = $this->entity->getValue($key);

//            if($key == 'homeImage') dd($value);

            $attribute->setValue($value);
        }


        $this->processAttributes();
    }

    /**
     * Fills the entity with the processed values form the attributes array.
     * Processing happens in each attributes by $attribute->getValue()
     * Eg. Hash::make in the Password attribute
     */
    protected function processAttributes()
    {
        foreach ($this->attributes as $attribute)
        {
            // Process the attribute
            $attribute->process();

            // Set entities value
            $this->entity->setValue($attribute->getKey(), $attribute->getValue());
        }
    }

    protected function deleteAttributes()
    {
        foreach ($this->attributes as $attribute)
        {
            $attribute->delete();
        }
    }

    /**
     * Translate the validation string in the Section
     * into an array with the validation rules
     *
     * @param $validation
     * @param null $languageId
     * @return Array|false
     */
    private function parseValidation($validation, $languageId = null)
    {
        if(! isset($validation['rules'])){
            return $validation;
        }
        $rule = $validation['rules'];
        $rule = $languageId ? str_replace('[[languageId]]',$languageId, $rule) : $rule;
        $rule = $this->entity->getId() ? str_replace('[[entityId]]', $this->entity->getId(), $rule) : str_replace('[[entityId]]','', $rule);

        // Replace [[routableId]] with the actual routableId
        $rule = method_exists($this->entity, 'getRoutableId') ? str_replace('[[routableId]]',$this->entity->getRoutableId($languageId), $rule) : $rule;

        // replace with the result of a method name in the entity
        foreach(get_class_methods($this->entity) as $methodName)
        {
            // check if the method name is in the template to prevent automatic method calls
            $pos = strpos($rule, '[['.$methodName.']]');
            if($pos !== false)
            {
                $rule = str_replace('[[' . $methodName . ']]', $this->entity->$methodName(), $rule);
            }
        }

        // replace with a property in the entity
        foreach(get_object_vars($this->entity) as $property => $value)
        {
            if(is_string($value))
            {
                $rule = str_replace('[[' . $property . ']]', $value, $rule);
            }
        }

        $validation['rules'] = $rule;

        return $validation;
    }

    private function parseOptions($options, $languageId = null)
    {
        foreach($options as $key => $option)
        {
            // Call recursively if the option is an array.
            if(is_array($option))
                $options[$key] = $this->parseOptions($option, $languageId);

            // Skip if option if isn't a string.
            if(! is_string($option)) continue;

            $options[$key] = $option = ($languageId != null) ? str_replace('[[languageId]]', $languageId, $option) : str_replace('[[languageId]]', '', $option);
            $options[$key] = $option = $this->entity->id ? str_replace('[[entityId]]', $this->entity->getId(), $option) : str_replace('[[entityId]]','', $option);

            // replace with the result of a method name in the entity
            foreach(get_class_methods($this->entity) as $methodName)
            {
                // check if the method name is in the template to prevent automatic method calls
                $pos = strpos($option, '[['.$methodName.']]');
                if($pos !== false)
                {
                    $options[$key] = $option = str_replace('[[' . $methodName . ']]', $this->entity->$methodName($languageId), $option);
                }
            }

            // replace with a property in the entity
            foreach(get_object_vars($this->entity) as $property => $value)
            {
                if(is_string($value))
                {
                    $options[$key] = $option = str_replace('[[' . $property . ']]', $value, $option);
                }
            }

        }
        return $options;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @param string $subTitle
     */
    public function setSubTitle($subTitle)
    {
        $this->subTitle = $subTitle;
    }

    /**
     * @param string $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }

    /**
     * @param mixed $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }




}