public function actionUpdate($message_id, $language)
    {
        $model = $this->findModel($message_id, $language);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(Yii::$app->request->isAjax)
                return $this->redirect(['index']);
            else
                return $this->redirect(['view', 'message_id' => $model->message_id, 'language' => $model->language]);
        } else {
            if(Yii::$app->request->isAjax)
                return $this->renderAjax('update', [
                    'model' => $model,
                ]);
            else
                return $this->render('update', [
                    'model' => $model,
                ]);
        }
    }

public function actionUpdate ( $ message_id , $ language ) { $ model = $ this -> findModel ( $ message_id , $ language ) ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> save ( ) ) { if ( Yii :: $ app -> request -> isAjax ) return $ this -> redirect ( [ 'index' ] ) ; else return $ this -> redirect ( [ 'view' , 'message_id' => $ model -> message_id , 'language' => $ model -> language ] ) ; } else { if ( Yii :: $ app -> request -> isAjax ) return $ this -> renderAjax ( 'update' , [ 'model' => $ model , ] ) ; else return $ this -> render ( 'update' , [ 'model' => $ model , ] ) ; } }

Updates an existing I18nTranslation model.
If update is successful, the browser will be redirected to the 'view' page.
@param integer $message_id
@param string $language
@return mixed

Updates an existing I18nTranslation model . If update is successful the browser will be redirected to the view page .


public function actionDelete($message_id, $language)
    {
        $this->findModel($message_id, $language)->delete();

        return $this->redirect(['index']);
    }

public function actionDelete ( $ message_id , $ language ) { $ this -> findModel ( $ message_id , $ language ) -> delete ( ) ; return $ this -> redirect ( [ 'index' ] ) ; }

Deletes an existing I18nTranslation model.
If deletion is successful, the browser will be redirected to the 'index' page.
@param integer $message_id
@param string $language
@return mixed

Deletes an existing I18nTranslation model . If deletion is successful the browser will be redirected to the index page .


protected function findModel($message_id, $language)
    {
        if (($model = I18nTranslation::findOne(['message_id' => $message_id, 'language' => $language])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

protected
function
findModel
(
$
message_id
,
$
language
)
{
if
(
(
$
model
=
I18nTranslation
::
findOne
(
[
'message_id'
=>
$
message_id
,
'language'
=>
$
language
]
)
)
!==
)
{
return
$
model
;
}
else
{
throw
new
NotFoundHttpException
(
'The requested page does not exist.'
)
;
}
}

Finds the I18nTranslation model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param integer $message_id
@param string $language
@return I18nTranslation the loaded model
@throws NotFoundHttpException if the model cannot be found

Finds the I18nTranslation model based on its primary key value . If the model is not found a 404 HTTP exception will be thrown .


public function listPagesCommand()
    {
        $pageRepository = new PageRepository();
        $pages = $pageRepository->findAll();
        $tableData = [];
        /** @var Page $page */
        foreach ($pages as $page) {
            $tableData[] = [
                'identifier'   => $page->getIdentifier(),
                'title'        => $page->getTitle(),
                'is directory' => $page->getIsDirectory(),
                'is virtual'   => $page->getIsVirtual(),
                'sorting'      => $page->getSorting(),
            ];
        }
        $this->outputTable($tableData);
    }

public
function
listPagesCommand
(
)
{
$
pageRepository
=
new
PageRepository
(
)
;
$
pages
=
$
pageRepository
->
findAll
(
)
;
$
tableData
=
[
]
;
/** @var Page $page */
foreach
(
$
pages
as
$
page
)
{
$
tableData
[
]
=
[
'identifier'
=>
$
page
->
getIdentifier
(
)
,
'title'
=>
$
page
->
getTitle
(
)
,
'is directory'
=>
$
page
->
getIsDirectory
(
)
,
'is virtual'
=>
$
page
->
getIsVirtual
(
)
,
'sorting'
=>
$
page
->
getSorting
(
)
,
]
;
}
$
this
->
outputTable
(
$
tableData
)
;
}


public function getContent()
    {
        if (!$this->parsedContent) {
            $this->parsedContent = MarkdownFactory::getMarkdownRenderer()->transform($this->getRawContent());
        }

        return $this->parsedContent;
    }

public function getContent ( ) { if ( ! $ this -> parsedContent ) { $ this -> parsedContent = MarkdownFactory :: getMarkdownRenderer ( ) -> transform ( $ this -> getRawContent ( ) ) ; } return $ this -> parsedContent ; }

Returns the parsed content

@return string


public function getSorting()
    {
        if (!$this->sorting) {
            $sorting = ObjectUtility::valueForKeyPathOfObject('meta.sorting', $this);
            if (!$sorting) {
                $sorting = self::DEFAULT_SORTING;
            }
            $this->sorting = $sorting;
        }

        return $this->sorting;
    }

public function getSorting ( ) { if ( ! $ this -> sorting ) { $ sorting = ObjectUtility :: valueForKeyPathOfObject ( 'meta.sorting' , $ this ) ; if ( ! $ sorting ) { $ sorting = self :: DEFAULT_SORTING ; } $ this -> sorting = $ sorting ; } return $ this -> sorting ; }

Returns the sorting position in a menu

@return int


public function getUri()
    {
        if (!$this->uri) {
            if (($url = $this->_getUrlFromMeta())) {
                $this->uri = $url;
            } else {
                if ($this->getIsVirtual()) {
                    $this->uri = '#';
                } else {
                    $uriParts = explode(DIRECTORY_SEPARATOR, $this->getIdentifier());
                    array_walk(
                        $uriParts,
                        function (&$uriPart) {
                            $uriPart = urlencode($uriPart);
                        }
                    );
                    $this->uri = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $uriParts) . DIRECTORY_SEPARATOR;
                }
            }
        }

        return $this->uri;
    }

public function getUri ( ) { if ( ! $ this -> uri ) { if ( ( $ url = $ this -> _getUrlFromMeta ( ) ) ) { $ this -> uri = $ url ; } else { if ( $ this -> getIsVirtual ( ) ) { $ this -> uri = '#' ; } else { $ uriParts = explode ( DIRECTORY_SEPARATOR , $ this -> getIdentifier ( ) ) ; array_walk ( $ uriParts , function ( & $ uriPart ) { $ uriPart = urlencode ( $ uriPart ) ; } ) ; $ this -> uri = DIRECTORY_SEPARATOR . implode ( DIRECTORY_SEPARATOR , $ uriParts ) . DIRECTORY_SEPARATOR ; } } } return $ this -> uri ; }

Returns the URI of the page

@return string


protected function _getUrlFromMeta()
    {
        $url = ObjectUtility::valueForKeyPathOfObject('meta.url', $this);
        if (!$url) {
            return null;
        }
        if (substr($url, 0, 11) === '/Resources/') {
            return $url;
        }
        if (substr($url, 0, 10) === 'Resources/') {
            return $url;
        }
        if (strpos($url, '://') === false) {
            $url = 'http://' . $url;
        }

        return $url;
    }

protected function _getUrlFromMeta ( ) { $ url = ObjectUtility :: valueForKeyPathOfObject ( 'meta.url' , $ this ) ; if ( ! $ url ) { return null ; } if ( substr ( $ url , 0 , 11 ) === '/Resources/' ) { return $ url ; } if ( substr ( $ url , 0 , 10 ) === 'Resources/' ) { return $ url ; } if ( strpos ( $ url , '://' ) === false ) { $ url = 'http://' . $ url ; } return $ url ; }

Returns the URL read from the meta data or NULL if it is not set

@return string


public function getTitle()
    {
        $title = ObjectUtility::valueForKeyPathOfObject('meta.title', $this);
        if (!$title) {
            $title = $this->getIdentifier();
            $slashPosition = strpos($title, DIRECTORY_SEPARATOR);
            if ($slashPosition !== false) {
                $title = substr($title, $slashPosition + 1);
            }
            $title = str_replace(self::URI_WHITESPACE_REPLACE, ' ', $title);
        }

        return $title;
    }

public
function
getTitle
(
)
{
$
title
=
ObjectUtility
::
valueForKeyPathOfObject
(
'meta.title'
,
$
this
)
;
if
(
!
$
title
)
{
$
title
=
$
this
->
getIdentifier
(
)
;
$
slashPosition
=
strpos
(
$
title
,
DIRECTORY_SEPARATOR
)
;
if
(
$
slashPosition
!==
false
)
{
$
title
=
substr
(
$
title
,
$
slashPosition
+
1
)
;
}
$
title
=
str_replace
(
self
::
URI_WHITESPACE_REPLACE
,
' '
,
$
title
)
;
}
return
$
title
;
}


public function get($apiMethod, $parameters = [])
    {
        $requestUrl = $this->buildUrl($apiMethod, $parameters);
        $requestUrl = urldecode($requestUrl);

        $response   = $this->getHttpClient()->get($requestUrl);

        return $this->handleResponse($response);
    }

public function get ( $ apiMethod , $ parameters = [ ] ) { $ requestUrl = $ this -> buildUrl ( $ apiMethod , $ parameters ) ; $ requestUrl = urldecode ( $ requestUrl ) ; $ response = $ this -> getHttpClient ( ) -> get ( $ requestUrl ) ; return $ this -> handleResponse ( $ response ) ; }

Send a GET request.

@param string $apiMethod
@param array  $parameters

@return object


private function buildUrl($apiMethod, $parameters)
    {
        switch ($this->getApiType()) {
            case 'Brand':
                $url = sprintf($this->apiUrlBrand, $this->getNetworkId(), $this->getApiNamespace(), $apiMethod, $this->getApiKey());
            break;

            case 'Affiliate':
                $url = sprintf($this->apiUrlAffiliate, $this->getNetworkId(), $this->getApiType(), $this->getApiNamespace(), $apiMethod, $this->getApiKey());
            break;
        }

        return $url.'&'.http_build_query($parameters);
    }

private function buildUrl ( $ apiMethod , $ parameters ) { switch ( $ this -> getApiType ( ) ) { case 'Brand' : $ url = sprintf ( $ this -> apiUrlBrand , $ this -> getNetworkId ( ) , $ this -> getApiNamespace ( ) , $ apiMethod , $ this -> getApiKey ( ) ) ; break ; case 'Affiliate' : $ url = sprintf ( $ this -> apiUrlAffiliate , $ this -> getNetworkId ( ) , $ this -> getApiType ( ) , $ this -> getApiNamespace ( ) , $ apiMethod , $ this -> getApiKey ( ) ) ; break ; } return $ url . '&' . http_build_query ( $ parameters ) ; }

Build the request url.

@param string $apiMethod
@param array  $parameter

@return string


private function handleResponse($response)
    {
        $statusCode = $response->getStatusCode();
        $body = json_decode($response->getBody());

        if ($statusCode >= 200 && $statusCode < 300) {
            return $body;
        }

        throw new \Exception($response->getBody(), $statusCode);
    }

private function handleResponse ( $ response ) { $ statusCode = $ response -> getStatusCode ( ) ; $ body = json_decode ( $ response -> getBody ( ) ) ; if ( $ statusCode >= 200 && $ statusCode < 300 ) { return $ body ; } throw new \ Exception ( $ response -> getBody ( ) , $ statusCode ) ; }

Handle the response.

@param object $response

@return object


static public function initializeConfiguration($basePath)
    {
        // Read the configurations file
        $configuration = [];
        $configurationFile = $basePath . 'Configurations/Configuration.json';
        if (file_exists($configurationFile) && is_readable($configurationFile)) {
            $configuration = json_decode(file_get_contents($configurationFile), true);
        }

        self::$sharedConfiguration = new Configuration($configuration);
        self::$sharedConfiguration->set('basePath', $basePath);

        return self::$sharedConfiguration;
    }

static
public
function
initializeConfiguration
(
$
basePath
)
{
// Read the configurations file
$
configuration
=
[
]
;
$
configurationFile
=
$
basePath
.
'Configurations/Configuration.json'
;
if
(
file_exists
(
$
configurationFile
)
&&
is_readable
(
$
configurationFile
)
)
{
$
configuration
=
json_decode
(
file_get_contents
(
$
configurationFile
)
,
true
)
;
}
self
::
$
sharedConfiguration
=
new
Configuration
(
$
configuration
)
;
self
::
$
sharedConfiguration
->
set
(
'basePath'
,
$
basePath
)
;
return
self
::
$
sharedConfiguration
;
}

Initializes the shared configuration

@param string $basePath
@return Configuration


static public function profile($message = null)
    {
        static $fileHandle = null;

        // Make sure the start time is defined
        if (!static::$startTime) {
            static::$startTime = microtime(true);
        }

        // Make sure the file handle exists
        if (!$fileHandle) {
            $fileHandle = fopen(static::$streamUri, 'w');
        }

        $output = sprintf('Profiler: %.4f', microtime(true) - static::$startTime);
        if ($message) {
            $output .= ' - ' . $message;
        }
        $output .= PHP_EOL;
        fwrite($fileHandle, $output);
    }

static
public
function
profile
(
$
message
=
)
{
static
$
fileHandle
=
;
// Make sure the start time is defined
if
(
!
static
::
$
startTime
)
{
static
::
$
startTime
=
microtime
(
true
)
;
}
// Make sure the file handle exists
if
(
!
$
fileHandle
)
{
$
fileHandle
=
fopen
(
static
::
$
streamUri
,
'w'
)
;
}
$
output
=
sprintf
(
'Profiler: %.4f'
,
microtime
(
true
)
static
::
$
startTime
)
;
if
(
$
message
)
{
$
output
.=
' - '
.
$
message
;
}
$
output
.=
PHP_EOL
;
fwrite
(
$
fileHandle
,
$
output
)
;
}

Show the processing time

@param string $message Optional profiling message


public function getTemplate()
    {
        if (file_exists($this->templatePath)) {
            return file_get_contents($this->templatePath);
        }

        return '<!-- Template file ' . $this->templatePath . ' not found -->' . PHP_EOL . '{content}';
    }

public
function
getTemplate
(
)
{
if
(
file_exists
(
$
this
->
templatePath
)
)
{
return
file_get_contents
(
$
this
->
templatePath
)
;
}
return
'<!-- Template file '
.
$
this
->
templatePath
.
' not found -->'
.
PHP_EOL
.
'{content}'
;
}


static public function valueForKeyPathOfObject($keyPath, $object, $default = null)
    {
        $i = 0;
        $keyPathParts = explode('.', $keyPath);
        $keyPathPartsLength = count($keyPathParts);
        $currentValue = $object;

        if (!is_string($keyPath)) {
            throw new \LogicException(
                'Given key path is not of type string (maybe arguments are ordered incorrect)',
                1395484136
            );
        }

        for ($i = 0; $i < $keyPathPartsLength; $i++) {
            $key = $keyPathParts[$i];
            $accessorMethod = 'get' . ucfirst($key);

            switch (true) {
                // Current value is an array
                case is_array($currentValue) && isset($currentValue[$key]):
                    $currentValue = $currentValue[$key];
                    break;

                // Current value is an object
                case is_object($currentValue):
                    if (method_exists($currentValue, $accessorMethod)) { // Getter method
                        $currentValue = $currentValue->$accessorMethod();
                    } else {
                        if (method_exists($currentValue, 'get')) { // General "get" method
                            $currentValue = $currentValue->get($key);
                        } else {
                            if (in_array($key, get_object_vars($currentValue))) { // Direct access
                                $currentValue = $currentValue->$key;
                            } else {
                                $currentValue = null;
                            }
                        }
                    }
                    break;

                default:
                    $currentValue = null;
            }

            if ($currentValue === null) {
                break;
            }
        }

        if ($i !== $keyPathPartsLength && func_num_args() > 2) {
            if (is_object($default) && ($default instanceof \Closure)) {
                $currentValue = $default();
            } else {
                $currentValue = $default;
            }
        }

        return $currentValue;
    }

Returns the value for the key path of the given object

@param string $keyPath      Key path of the property to fetch
@param object|array $object Source to fetch the data from
@param mixed $default       An optional default value to return if the path could not be resolved. If a callback is passed, it's return value is used
@throws \LogicException if the given key path is no string
@return mixed


public function setRootDirectory($directory)
    {
        if (!is_dir($directory)) {
            throw new \DomainException(sprintf(
                'The value "%s" defined as the root directory does not exist.',
                $directory
            ));
        }
        $this->directory = $directory;
        return $this;
    }

Set Root Directory

@access public
@throws \DomainException
@param string $directory
@return self


public function findClassReflections($subDir = null, $suffix = null, $parent = null, $allowedParameters = 0)
    {
        $classes = [];
        $subDir = trim(preg_replace('#//{2,}#', '/', strtr($subDir, '\\', '/')), '/');
        $namespace = trim($this->namespace, '\\') . '\\' . strtr($subDir, '/', '\\') . '\\';
        $finder = $this->directory !== null
               && is_dir($directory = $this->directory . DIRECTORY_SEPARATOR . strtr($subDir, '/', DIRECTORY_SEPARATOR))
            ? (new Finder)->files()->name(sprintf('*%s', $this->extension))->in($directory)
            : [];
        foreach ($finder as $file) {
            try {
                $class = $this->getClassReflection($file, $namespace, $suffix, $parent, $allowedParameters);
                $classes[] = $class;
            } catch (\Exception $exception) {
                continue;
            }
        }
        return $classes;
    }

public function findClassReflections ( $ subDir = null , $ suffix = null , $ parent = null , $ allowedParameters = 0 ) { $ classes = [ ] ; $ subDir = trim ( preg_replace ( '#//{2,}#' , '/' , strtr ( $ subDir , '\\' , '/' ) ) , '/' ) ; $ namespace = trim ( $ this -> namespace , '\\' ) . '\\' . strtr ( $ subDir , '/' , '\\' ) . '\\' ; $ finder = $ this -> directory !== null && is_dir ( $ directory = $ this -> directory . DIRECTORY_SEPARATOR . strtr ( $ subDir , '/' , DIRECTORY_SEPARATOR ) ) ? ( new Finder ) -> files ( ) -> name ( sprintf ( '*%s' , $ this -> extension ) ) -> in ( $ directory ) : [ ] ; foreach ( $ finder as $ file ) { try { $ class = $ this -> getClassReflection ( $ file , $ namespace , $ suffix , $ parent , $ allowedParameters ) ; $ classes [ ] = $ class ; } catch ( \ Exception $ exception ) { continue ; } } return $ classes ; }

Find Class Reflections

@access public
@param string $subDir
@param string $suffix
@param string $parent
@param integer $allowedParameters
@return array


protected function getClassReflection(SplFileInfo $file, $namespace, $suffix, $parent, $allowedParameters)
    {
        // Determine the fully-qualified class name of the found file.
        $class = preg_replace('#\\\\{2,}#', '\\', sprintf(
            '%s\\%s\\%s',
            $namespace,
            strtr($file->getRelativePath(), '/', '\\'),
            $file->getBasename($this->extension)
        ));
        // Make sure that the class name has the correct suffix.
        if (!empty($suffix) && substr($class, 0 - strlen($suffix)) !== $suffix) {
            throw new \LogicException(sprintf(
                'The file found at "%s" does not end with the required suffix of "%s".',
                $file->getRealPath(),
                $suffix
            ));
        }
        // We have to perform a few checks on the class before we can return it.
        // - It must be an actual class; not interface, abstract or trait types.
        // - For this to work the constructor must not have more than the expected number of required parameters.
        // - And finally make sure that the class loaded was actually loaded from the directory we found it in.
        //   TODO: Make sure that the final (file path) check doesn't cause problems with proxy classes or
        //         bootstraped/compiled class caches.
        $reflect = new ReflectionClass($class, $file->getRelativePath());
        if ((is_object($construct = $reflect->getConstructor())
                && $construct->getNumberOfRequiredParameters() > $allowedParameters
            )
            || $reflect->isAbstract() || $reflect->isInterface() || $reflect->isTrait()
            || (is_string($parent) && !empty($parent) && !$reflect->isSubclassOf($parent))
            || $reflect->getFileName() !== $file->getRealPath()
        ) {
            throw new \LogicException(sprintf('The class definition for "%s" is invalid.', $class));
        }
        return $reflect;
    }

//         bootstraped/compiled class caches.

Get Class Reflection Instance

@access protected
@throws \LogicException
@param \Symfony\Component\Finder\SplFileInfo $file
@param string $namespace
@param string $suffix
@param string $parent
@param integer $allowedParameters
@return \Darsyn\ClassFinder\Reflection\ReflectionClass


public function mediaUpload($fileName = 'file', $useFile = false)
    {
        $file = UploadedFile::getInstanceByName($fileName);

        if ($useFile !== false) {
            $file = $file[0];
        }

        if (is_null($file)) {
            throw new BadRequestHttpException('No file specified to upload.');
        }

        return $this->insertMedia($file);
    }

public
function
mediaUpload
(
$
fileName
=
'file'
,
$
useFile
=
false
)
{
$
file
=
UploadedFile
::
getInstanceByName
(
$
fileName
)
;
if
(
$
useFile
!==
false
)
{
$
file
=
$
file
[
0
]
;
}
if
(
is_null
(
$
file
)
)
{
throw
new
BadRequestHttpException
(
'No file specified to upload.'
)
;
}
return
$
this
->
insertMedia
(
$
file
)
;
}

Uploads the file
if success returns json array for media data

@param string $fileName
@param bool $useFile
@return bool|string
@throws \yii\web\BadRequestHttpException


private function insertMedia($file)
    {
        /**
         * @var \yii\web\UploadedFile $file
         */

        $result = ['success' => false, 'message' => 'File could not be saved.'];

        if ($file->size > Yii::$app->params['maxUploadSize']) {
            $result['message'] = 'Max upload size limit reached';
        }

        $uploadTime = date("Y-m-W");
        $media = new MediaModel();

        $media->filename = KatoBase::sanitizeFile($file->baseName) . '-' . KatoBase::genRandomString(4) . '.' . $file->extension;
        $media->mimeType = $file->type;
        $media->byteSize = $file->size;
        $media->extension = $file->extension;
        $media->source = basename(\Yii::$app->params['uploadPath']) . '/' . $uploadTime . '/' . $media->filename;

        if (!is_file($media->source)) {
            //If saved upload the file
            $uploadPath = \Yii::$app->params['uploadPath'] . $uploadTime;
            if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true);

            if ($file->saveAs($uploadPath . '/' . $media->filename)) {
                //Save to media table
                if ($media->save(false)) {
                    $result['success'] = true;
                    $result['message'] = 'Upload Success';
                    $result['data'] = $media;
                } else {
                    $result['message'] = "Database record could not be saved.";
                }
            } else {
                $result['message'] = "File could not be saved.";
            }
        } else {
            $result['message'] = "File already exists.";
        }

        return $result;
    }

Upload to file and insert into media table
@param $file
@return array


public function hours($downTo=15, $decimalPlaces=2)
    {
        if (! $this->has(['start','end']))
            return 0;

        $diff = $this->start->diffInMinutes($this->end);
        $minutes = $diff - ($downTo / 2);

        $hours = $minutes / 60;
        $periodsPerHour = 60 / $downTo;
        $roundedHours = round(
            round($hours * $periodsPerHour) / $periodsPerHour,
            $decimalPlaces
        );

        $whole = floor($roundedHours);
        $fraction = round($roundedHours - $whole,2);
        $periodLength = round(1.0 / $periodsPerHour,2);

        if ($fraction == $periodLength && $diff % $downTo === 0)
            return ($roundedHours - $periodLength);

        return $roundedHours;
    }

public function hours ( $ downTo = 15 , $ decimalPlaces = 2 ) { if ( ! $ this -> has ( [ 'start' , 'end' ] ) ) return 0 ; $ diff = $ this -> start -> diffInMinutes ( $ this -> end ) ; $ minutes = $ diff - ( $ downTo / 2 ) ; $ hours = $ minutes / 60 ; $ periodsPerHour = 60 / $ downTo ; $ roundedHours = round ( round ( $ hours * $ periodsPerHour ) / $ periodsPerHour , $ decimalPlaces ) ; $ whole = floor ( $ roundedHours ) ; $ fraction = round ( $ roundedHours - $ whole , 2 ) ; $ periodLength = round ( 1.0 / $ periodsPerHour , 2 ) ; if ( $ fraction == $ periodLength && $ diff % $ downTo === 0 ) return ( $ roundedHours - $ periodLength ) ; return $ roundedHours ; }

Round down to the nearest 15 minutes
As a special case, round the first period
down to 0.

Round down to the nearest 15 minutes As a special case round the first period down to 0 .


public function getDirtyData(
        array $newSerializedModel,
        array $oldSerializedModel,
        ClassMetadata $classMetadata
    ): array {
        return $this->getDirtyFields(
            $newSerializedModel,
            $oldSerializedModel,
            $classMetadata
        );
    }

public function getDirtyData ( array $ newSerializedModel , array $ oldSerializedModel , ClassMetadata $ classMetadata ) : array { return $ this -> getDirtyFields ( $ newSerializedModel , $ oldSerializedModel , $ classMetadata ) ; }

return the new serialized model with only needed fields to update


public function registerClean(string $id, object $entity): self
    {
        $entityStored = clone $entity;
        $this->storage[$id] = $entityStored;

        return $this;
    }

public function registerClean ( string $ id , object $ entity ) : self { $ entityStored = clone $ entity ; $ this -> storage [ $ id ] = $ entityStored ; return $ this ; }

Register a net entity in the UnitOfWork storage


private function getDirtyFields(
        array $newSerializedModel,
        array $oldSerializedModel,
        ClassMetadata $classMetadata
    ): array {
        $dirtyFields = [];

        foreach ($newSerializedModel as $key => $value) {
            if (!array_key_exists($key, $oldSerializedModel)) {
                // a new key has been found, add it to the dirtyFields
                $dirtyFields[$key] = $value;
                continue;
            }

            $oldValue = $oldSerializedModel[$key];

            $currentRelation = $classMetadata->getRelation($key);

            if (!$currentRelation) {
                if (
                    is_array($value) &&
                    !ArrayHelper::arraySame($value, $oldValue ?: []) ||
                    $value !== $oldValue
                ) {
                    $dirtyFields[$key] = $value;
                }
                continue;
            }

            $currentClassMetadata = $this->mapping->getClassMetadata(
                $currentRelation->getTargetEntity()
            );

            $idSerializedKey = $currentClassMetadata->getIdSerializeKey();

            if (Relation::MANY_TO_ONE === $currentRelation->getType()) {
                if ($value !== $oldValue) {
                    if (is_string($value) || is_string($oldValue)) {
                        $dirtyFields[$key] = $value;
                    } else {
                        $recursiveDiff = $this->getDirtyFields(
                            $value,
                            $oldValue,
                            $currentClassMetadata
                        );

                        if (!empty($recursiveDiff)) {
                            $recursiveDiff[
                                $idSerializedKey
                            ] = self::getEntityId($value, $idSerializedKey);
                            $dirtyFields[$key] = $recursiveDiff;
                        }
                    }
                }

                continue;
            }

            // ONE_TO_MANY relation
            if (count($value ?? []) !== count($oldValue ?? [])) {
                // get all objects ids of new array
                $dirtyFields[$key] = $this->addIdentifiers(
                    $value,
                    [],
                    $idSerializedKey
                );
            }

            if (!empty($value)) {
                foreach ($value as $relationKey => $relationValue) {
                    $oldRelationValue = $this->findOldRelation(
                        $relationValue,
                        $oldValue,
                        $currentClassMetadata
                    );

                    if ($relationValue !== $oldRelationValue) {
                        if (
                            is_string($relationValue) ||
                            is_string($oldRelationValue)
                        ) {
                            $dirtyFields[$key][$relationKey] = $relationValue;
                        } else {
                            $recursiveDiff = $this->getDirtyFields(
                                $relationValue,
                                $oldRelationValue,
                                $currentClassMetadata
                            );

                            if (!empty($recursiveDiff)) {
                                $idSerializedKey = $currentClassMetadata->getIdSerializeKey();

                                $entityId = self::getEntityId(
                                    $relationValue,
                                    $idSerializedKey
                                );
                                if (null !== $entityId) {
                                    $recursiveDiff[
                                        $idSerializedKey
                                    ] = $entityId;
                                }
                                $dirtyFields[$key][
                                    $relationKey
                                ] = $recursiveDiff;
                            }
                        }
                    }
                }
            }
        }

        return $dirtyFields;
    }

Compare serialize object and returns only modified fields


private function addIdentifiers(
        $newSerializedModel,
        array $dirtyFields,
        $idSerializedKey = null
    ): array {
        foreach ($newSerializedModel as $key => $value) {
            if ($idSerializedKey && isset($value[$idSerializedKey])) {
                $dirtyFields[$key][$idSerializedKey] = $value[$idSerializedKey];
            } elseif (is_string($value) && is_int($key)) {
                $dirtyFields[$key] = $value;
            }
        }

        return $dirtyFields;
    }

private function addIdentifiers ( $ newSerializedModel , array $ dirtyFields , $ idSerializedKey = null ) : array { foreach ( $ newSerializedModel as $ key => $ value ) { if ( $ idSerializedKey && isset ( $ value [ $ idSerializedKey ] ) ) { $ dirtyFields [ $ key ] [ $ idSerializedKey ] = $ value [ $ idSerializedKey ] ; } elseif ( is_string ( $ value ) && is_int ( $ key ) ) { $ dirtyFields [ $ key ] = $ value ; } } return $ dirtyFields ; }

add defined identifiers to given model

@param ?mixed $idSerializedKey


private static function getEntityId(
        $stringOrEntity,
        string $idSerializedKey
    ) {
        if (!is_array($stringOrEntity)) {
            return $stringOrEntity;
        }

        return $stringOrEntity[$idSerializedKey] ?? null;
    }

private static function getEntityId ( $ stringOrEntity , string $ idSerializedKey ) { if ( ! is_array ( $ stringOrEntity ) ) { return $ stringOrEntity ; } return $ stringOrEntity [ $ idSerializedKey ] ?? null ; }

get entity id from string or array

@param string|array $stringOrEntity
@param string $idSerializedKey

@return ?mixed


private function getTags()
    {
        $allTags = $this->getAllTags()->all();
        $tags = '';

        $total=0;
        foreach ($allTags as $tag) {
            $total += $tag->frequency;
        }

        foreach($allTags as $tag) {
            $weight = 8 + (int)(16*$tag->frequency/($total+10));
            $this->options['style'] = "font-size:{$weight}pt";

            if (isset($_GET[$this->get_real_class($this->model)]['tags']) && $_GET[$this->get_real_class($this->model)]['tags'] === $tag->name) {
                $this->options['class'] = 'tag active';
            } else {
                $this->options['class'] = 'tag';
            }
            $tags .= Html::tag('li', Html::a($tag->name, ['/blog/index', $this->get_real_class($this->model) . '[tags]' => $tag->name]), $this->options);
        }

        $tags .= Html::tag('li', '', ['class' => 'clearfix']);

        return $tags;
    }

private
function
getTags
(
)
{
$
allTags
=
$
this
->
getAllTags
(
)
->
all
(
)
;
$
tags
=
''
;
$
total
=
0
;
foreach
(
$
allTags
as
$
tag
)
{
$
total
+=
$
tag
->
frequency
;
}
foreach
(
$
allTags
as
$
tag
)
{
$
weight
=
8
+
(
int
)
(
16
*
$
tag
->
frequency
/
(
$
total
+
10
)
)
;
$
this
->
options
[
'style'
]
=
"font-size:{$weight}pt"
;
if
(
isset
(
$
_GET
[
$
this
->
get_real_class
(
$
this
->
model
)
]
[
'tags'
]
)
&&
$
_GET
[
$
this
->
get_real_class
(
$
this
->
model
)
]
[
'tags'
]
===
$
tag
->
name
)
{
$
this
->
options
[
'class'
]
=
'tag active'
;
}
else
{
$
this
->
options
[
'class'
]
=
'tag'
;
}
$
tags
.=
Html
::
tag
(
'li'
,
Html
::
a
(
$
tag
->
name
,
[
'/blog/index'
,
$
this
->
get_real_class
(
$
this
->
model
)
.
'[tags]'
=>
$
tag
->
name
]
)
,
$
this
->
options
)
;
}
$
tags
.=
Html
::
tag
(
'li'
,
''
,
[
'class'
=>
'clearfix'
]
)
;
return
$
tags
;
}

Returns list of tags from model
@return string


private function get_real_class($obj) {
        $classname = get_class($obj);

        if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
            $classname = $matches[1];
        }

        return $classname;
    }

private function get_real_class ( $ obj ) { $ classname = get_class ( $ obj ) ; if ( preg_match ( '@\\\\([\w]+)$@' , $ classname , $ matches ) ) { $ classname = $ matches [ 1 ] ; } return $ classname ; }

Obtains an object class name without namespaces
@param $obj
@return string


private function configureTabElementFactory(ContainerBuilder $container): void
    {
        $definition = $container->findDefinition(TabElementFactory::class);
        if (!$definition) {
            return;
        }

        $bundles = $container->getParameter('kernel.bundles');

        if (!isset($bundles['ContaoBootstrapGridBundle'])) {
            return;
        }

        $definition->setArgument(5, new Reference('contao_bootstrap.grid.grid_provider'));
    }

private function configureTabElementFactory ( ContainerBuilder $ container ) : void { $ definition = $ container -> findDefinition ( TabElementFactory :: class ) ; if ( ! $ definition ) { return ; } $ bundles = $ container -> getParameter ( 'kernel.bundles' ) ; if ( ! isset ( $ bundles [ 'ContaoBootstrapGridBundle' ] ) ) { return ; } $ definition -> setArgument ( 5 , new Reference ( 'contao_bootstrap.grid.grid_provider' ) ) ; }

Configure the tab element factory.

@param ContainerBuilder $container The container builder.

@return void


public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            //Remove file from system
            if (file_exists($this->baseSource)) {
                unlink($this->baseSource);
            }

            //Delete from relation table
            if ($contentMedia = ContentMedia::find()->where(['media_id' => $this->id])->all()) {
                foreach ($contentMedia as $data) {
                    $data->delete();
                }
            }

            return true;
        }

        return false;
    }

public
function
beforeDelete
(
)
{
if
(
parent
::
beforeDelete
(
)
)
{
//Remove file from system
if
(
file_exists
(
$
this
->
baseSource
)
)
{
unlink
(
$
this
->
baseSource
)
;
}
//Delete from relation table
if
(
$
contentMedia
=
ContentMedia
::
find
(
)
->
where
(
[
'media_id'
=>
$
this
->
id
]
)
->
all
(
)
)
{
foreach
(
$
contentMedia
as
$
data
)
{
$
data
->
delete
(
)
;
}
}
return
true
;
}
return
false
;
}

Before deletion, remove media file from source and also delete from relation table
@inheritdoc

Before deletion remove media file from source and also delete from relation table


private function createTitle()
    {
        $title_parts = pathinfo($this->filename);
        $this->title = $title_parts['filename'];
        $this->title = \kato\helpers\KatoBase::sanitizeFile($this->title);
        $this->title = str_replace('_', ' ', str_replace('-', ' ', $this->title));
        $this->title = ucwords($this->title);
    }

private
function
createTitle
(
)
{
$
title_parts
=
pathinfo
(
$
this
->
filename
)
;
$
this
->
title
=
$
title_parts
[
'filename'
]
;
$
this
->
title
=
\
kato
\
helpers
\
KatoBase
::
sanitizeFile
(
$
this
->
title
)
;
$
this
->
title
=
str_replace
(
'_'
,
' '
,
str_replace
(
'-'
,
' '
,
$
this
->
title
)
)
;
$
this
->
title
=
ucwords
(
$
this
->
title
)
;
}


public function renderPdf($data = [])
    {
        if (isset($data['imgTag'])) {
            $pdfPreview = Yii::$app->request->baseUrl . '/theme-assets/img/pdf-preview.jpg';

            $options = [];
            if (isset($data['width'])) $options['width'] = $data['width'];
            if (isset($data['height'])) $options['height'] = $data['height'];
            return Html::img($pdfPreview, $options);
        }

        return '/' . $this->source;
    }

public function renderPdf ( $ data = [ ] ) { if ( isset ( $ data [ 'imgTag' ] ) ) { $ pdfPreview = Yii :: $ app -> request -> baseUrl . '/theme-assets/img/pdf-preview.jpg' ; $ options = [ ] ; if ( isset ( $ data [ 'width' ] ) ) $ options [ 'width' ] = $ data [ 'width' ] ; if ( isset ( $ data [ 'height' ] ) ) $ options [ 'height' ] = $ data [ 'height' ] ; return Html :: img ( $ pdfPreview , $ options ) ; } return '/' . $ this -> source ; }

Renders PDF File
@param array $data
@return string


public function renderImage($data = [])
    {
        ini_set('memory_limit', '512M');
        $cacheFile = Yii::getAlias('@cachePath/' . $this->filename);
        $baseSource = $this->baseSource;

        if (!isset($data['width']) && !isset($data['height'])) {
            if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $this->filename))) {
                //only cache if not available
                try {
                    $image = Image::getImagine();
                    $newImage = $image->open($baseSource);
                    $newImage->save($cacheFile);
                } catch (\Exception $e) {
                    //seems like image is corrupt!
                }
            }

            return Yii::getAlias('@cacheDir/' . $this->filename);
        } else {
            $path_parts = pathinfo($cacheFile);
            $newFileName = $path_parts['filename'] . '-' . $data['width'] . '-' . $data['height'] . '.' . $path_parts['extension'];
            //http://imagine.readthedocs.org/en/latest/
            if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $newFileName))) {
                //only cache if not available
                try {
                    Image::thumbnail($baseSource, $data['width'], $data['height'])
                        ->save(Yii::getAlias('@cachePath/' . $newFileName));
                } catch (\Exception $e) {
                    //seems like image is corrupt!
                }
            }

            if (isset($data['imgTag'])) {
                return Html::img(Yii::getAlias('@cacheDir/' . $newFileName));
            } else {
                return Yii::getAlias('@cacheDir/' . $newFileName);
            }
        }
    }

Renders all supported image files
@param array $data
@return bool|string


public function hydrate(?array $data, string $modelName): ?object
    {
        $mapping = $this->sdk->getMapping();
        $key = $mapping->getKeyFromModel($modelName);
        $modelName = $mapping->getModelName($key);

        return $this->deserialize($data, $modelName);
    }

public function hydrate ( ? array $ data , string $ modelName ) : ? object { $ mapping = $ this -> sdk -> getMapping ( ) ; $ key = $ mapping -> getKeyFromModel ( $ modelName ) ; $ modelName = $ mapping -> getModelName ( $ key ) ; return $ this -> deserialize ( $ data , $ modelName ) ; }


public function hydrateList(?array $data, string $modelName): Collection
    {
        $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey'];

        if (is_array($data) && ArrayHelper::arrayHas($data, $collectionKey)) {
            return $this->deserializeAll($data, $modelName);
        }

        return new Collection();
    }

public function hydrateList ( ? array $ data , string $ modelName ) : Collection { $ collectionKey = $ this -> sdk -> getMapping ( ) -> getConfig ( ) [ 'collectionKey' ] ; if ( is_array ( $ data ) && ArrayHelper :: arrayHas ( $ data , $ collectionKey ) ) { return $ this -> deserializeAll ( $ data , $ modelName ) ; } return new Collection ( ) ; }

convert API response to Collection containing entities


private function deserializeAll(array $data, string $modelName): Collection
    {
        $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey'];

        $itemList = array_map(function ($member) use ($modelName) {
            return $this->deserialize($member, $modelName);
        }, ArrayHelper::arrayGet($data, $collectionKey));

        $extraProperties = array_filter(
            $data,
            function ($key) use ($collectionKey) {
                return $key !== $collectionKey;
            },
            ARRAY_FILTER_USE_KEY
        );

        $collectionClassName = $this->guessCollectionClassname($data);

        return new $collectionClassName($itemList, $extraProperties);
    }

private function deserializeAll ( array $ data , string $ modelName ) : Collection { $ collectionKey = $ this -> sdk -> getMapping ( ) -> getConfig ( ) [ 'collectionKey' ] ; $ itemList = array_map ( function ( $ member ) use ( $ modelName ) { return $ this -> deserialize ( $ member , $ modelName ) ; } , ArrayHelper :: arrayGet ( $ data , $ collectionKey ) ) ; $ extraProperties = array_filter ( $ data , function ( $ key ) use ( $ collectionKey ) { return $ key !== $ collectionKey ; } , ARRAY_FILTER_USE_KEY ) ; $ collectionClassName = $ this -> guessCollectionClassname ( $ data ) ; return new $ collectionClassName ( $ itemList , $ extraProperties ) ; }

convert list of data as array to Collection containing entities


private function deserialize(?array $data, string $modelName): ?object
    {
        if (null === $data) {
            return null;
        }

        return $this->sdk->getSerializer()->deserialize($data, $modelName);
    }

private function deserialize ( ? array $ data , string $ modelName ) : ? object { if ( null === $ data ) { return null ; } return $ this -> sdk -> getSerializer ( ) -> deserialize ( $ data , $ modelName ) ; }


private function guessCollectionClassname(array $data): string
    {
        switch (true) {
            case !empty($data['@type']) &&
            'hydra:PagedCollection' === $data['@type']:
                return HydraPaginatedCollection::class;

            case array_key_exists('_embedded', $data):
                return HalCollection::class;

            default:
                return Collection::class;
        }
    }

private function guessCollectionClassname ( array $ data ) : string { switch ( true ) { case ! empty ( $ data [ '@type' ] ) && 'hydra:PagedCollection' === $ data [ '@type' ] : return HydraPaginatedCollection :: class ; case array_key_exists ( '_embedded' , $ data ) : return HalCollection :: class ; default : return Collection :: class ; } }

guess collection classname according to response data


public function buildSitemap($returnAsArray = false)
    {
        $urls = $this->urls;
        foreach ($this->models as $modelName) {
            /** @var \kato\modules\sitemap\behaviors\SitemapBehavior $model */
            if (is_array($modelName)) {
                $model = new $modelName['class'];
                if (isset($modelName['behaviors'])) {
                    $model->attachBehaviors($modelName['behaviors']);
                }
            } else {
                $model = new $modelName;
            }
            $urls = array_merge($urls, $model->generateSiteMap());
        }

        if ($returnAsArray === true) {
            return $urls;
        }

        $sitemapData = $this->createControllerByID('default')->renderPartial('index', [
            'urls' => $urls
        ]);

        $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire);
        return $sitemapData;
    }

Build and cache a site map.
@param bool $returnAsArray
@return array|string
@throws InvalidConfigException


public function getNavigation(string $elementId): Navigation
    {
        if (!isset($this->navigations[$elementId])) {
            $element = ContentModel::findByPk($elementId);
            Assertion::isInstanceOf($element, ContentModel::class);
            Assertion::eq($element->type, 'bs_tab_start');

            $this->navigations[$elementId] = Navigation::fromSerialized((string) $element->bs_tabs, $elementId);
        }

        return $this->navigations[$elementId];
    }

public function getNavigation ( string $ elementId ) : Navigation { if ( ! isset ( $ this -> navigations [ $ elementId ] ) ) { $ element = ContentModel :: findByPk ( $ elementId ) ; Assertion :: isInstanceOf ( $ element , ContentModel :: class ) ; Assertion :: eq ( $ element -> type , 'bs_tab_start' ) ; $ this -> navigations [ $ elementId ] = Navigation :: fromSerialized ( ( string ) $ element -> bs_tabs , $ elementId ) ; } return $ this -> navigations [ $ elementId ] ; }

Get a navigation.

@param string $elementId The element id.

@return Navigation

@throws \Assert\AssertionFailedException When an invalid element is given.


public function getIterator(string $elementId): NavigationIterator
    {
        if (!isset($this->iterators[$elementId])) {
            $this->iterators[$elementId] = new NavigationIterator($this->getNavigation($elementId));
        }

        return $this->iterators[$elementId];
    }

public function getIterator ( string $ elementId ) : NavigationIterator { if ( ! isset ( $ this -> iterators [ $ elementId ] ) ) { $ this -> iterators [ $ elementId ] = new NavigationIterator ( $ this -> getNavigation ( $ elementId ) ) ; } return $ this -> iterators [ $ elementId ] ; }

Get the iterator.

@param string $elementId The element id.

@return NavigationIterator

@throws \Assert\AssertionFailedException When an invalid element is given.


public function normalize()
    {
        if (!empty($this->owner->{$this->attribute})) {
            $this->owner->{$this->attribute} = $this->array2string(array_unique($this->string2array($this->owner->{$this->attribute})));
        }
    }

public function normalize ( ) { if ( ! empty ( $ this -> owner -> { $ this -> attribute } ) ) { $ this -> owner -> { $ this -> attribute } = $ this -> array2string ( array_unique ( $ this -> string2array ( $ this -> owner -> { $ this -> attribute } ) ) ) ; } }


public function getExtraProperty(string $key)
    {
        if (isset($this->extraProperties[$key])) {
            return $this->extraProperties[$key];
        }
    }

public function getExtraProperty ( string $ key ) { if ( isset ( $ this -> extraProperties [ $ key ] ) ) { return $ this -> extraProperties [ $ key ] ; } }

return the value of an extra property

@return mixed


public static function genRandomString($length=8) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        $size = strlen( $chars );
        $str='';
        for( $i = 0; $i < $length; $i++ ) {
            $str .= $chars[ rand( 0, $size - 1 ) ];
        }

        return $str;
    }

Creates random string
default lenght is 8


public static function limit_words($string, $word_limit)
    {
        $words = explode(' ',$string);
        return trim(implode(' ', array_splice($words, 0, $word_limit))) .'...';
    }

public
static
function
limit_words
(
$
string
,
$
word_limit
)
{
$
words
=
explode
(
' '
,
$
string
)
;
return
trim
(
implode
(
' '
,
array_splice
(
$
words
,
0
,
$
word_limit
)
)
)
.
'...'
;
}

Helper function to limit the words in a string

@param string $string the given string
@param int $word_limit the number of words to limit to
@return string the limited string


public static function get_files($directory, $ext = '')
    {
        $array_items = array();
        if($handle = opendir($directory)){
            while(false !== ($file = readdir($handle))){
                if($file != "." && $file != ".."){
                    if(is_dir($directory. "/" . $file)){
                        $array_items = array_merge($array_items, self::get_files($directory. "/" . $file, $ext));
                    } else {
                        $file = $directory . "/" . $file;
                        if(!$ext || strstr($file, $ext)) $array_items[] = preg_replace("/\/\//si", "/", $file);
                    }
                }
            }
            closedir($handle);
        }
        return $array_items;
    }

public static function get_files ( $ directory , $ ext = '' ) { $ array_items = array ( ) ; if ( $ handle = opendir ( $ directory ) ) { while ( false !== ( $ file = readdir ( $ handle ) ) ) { if ( $ file != "." && $ file != ".." ) { if ( is_dir ( $ directory . "/" . $ file ) ) { $ array_items = array_merge ( $ array_items , self :: get_files ( $ directory . "/" . $ file , $ ext ) ) ; } else { $ file = $ directory . "/" . $ file ; if ( ! $ ext || strstr ( $ file , $ ext ) ) $ array_items [ ] = preg_replace ( "/\/\//si" , "/" , $ file ) ; } } } closedir ( $ handle ) ; } return $ array_items ; }

Helper function to recusively get all files in a directory

@param string $directory start directory
@param string $ext optional limit to file extensions
@return array the matched files


public static function genShortDesc($content, $tag = 'p' , $wordLimit = 20)
    {
        if (preg_match('%(<' . $tag . '[^>]*>.*?</' . $tag . '>)%i', $content, $regs)) {
            $result = $regs[1];
        } else {
            $result = "";
        }

        return self::limit_words(strip_tags($result), $wordLimit);
    }

public static function genShortDesc ( $ content , $ tag = 'p' , $ wordLimit = 20 ) { if ( preg_match ( '%(<' . $ tag . '[^>]*>.*?</' . $ tag . '>)%i' , $ content , $ regs ) ) { $ result = $ regs [ 1 ] ; } else { $ result = "" ; } return self :: limit_words ( strip_tags ( $ result ) , $ wordLimit ) ; }

Strip tags and limit description
@param $content
@param string $tag
@param int $wordLimit
@return string


public function isOverlap(TimeSlotInterface $baseTimeSlot, TimeSlotInterface $overlappingTimeSlot)
    {
        return $baseTimeSlot->getStart() < $overlappingTimeSlot->getEnd()
               && $overlappingTimeSlot->getStart() < $baseTimeSlot->getEnd();
    }

public function isOverlap ( TimeSlotInterface $ baseTimeSlot , TimeSlotInterface $ overlappingTimeSlot ) { return $ baseTimeSlot -> getStart ( ) < $ overlappingTimeSlot -> getEnd ( ) && $ overlappingTimeSlot -> getStart ( ) < $ baseTimeSlot -> getEnd ( ) ; }

Check if given time slots overlap

@param TimeSlotInterface $baseTimeSlot
@param TimeSlotInterface $overlappingTimeSlot

@return bool


public function getNonOverlappedTimeSlots(
        TimeSlotInterface $baseTimeSlot,
        array $overlappingTimeSlots,
        TimeSlotGeneratorInterface $timeSlotGenerator
    ) {
        $baseTimeSlots = [
            $timeSlotGenerator->createTimeSlot($baseTimeSlot->getStart(), $baseTimeSlot->getEnd()),
        ];

        foreach ($overlappingTimeSlots as $overlappingTimeSlot) {
            $freeTimeSlots = [];
            foreach ($baseTimeSlots as $timeSlot) {
                $freeTimeSlots =  array_merge(
                    $freeTimeSlots,
                    $this->fetchNonOverlappedTimeSlots($timeSlot, $overlappingTimeSlot, $timeSlotGenerator)
                );
            }

            $baseTimeSlots = $freeTimeSlots;
        }

        return $baseTimeSlots;
    }

public function getNonOverlappedTimeSlots ( TimeSlotInterface $ baseTimeSlot , array $ overlappingTimeSlots , TimeSlotGeneratorInterface $ timeSlotGenerator ) { $ baseTimeSlots = [ $ timeSlotGenerator -> createTimeSlot ( $ baseTimeSlot -> getStart ( ) , $ baseTimeSlot -> getEnd ( ) ) , ] ; foreach ( $ overlappingTimeSlots as $ overlappingTimeSlot ) { $ freeTimeSlots = [ ] ; foreach ( $ baseTimeSlots as $ timeSlot ) { $ freeTimeSlots = array_merge ( $ freeTimeSlots , $ this -> fetchNonOverlappedTimeSlots ( $ timeSlot , $ overlappingTimeSlot , $ timeSlotGenerator ) ) ; } $ baseTimeSlots = $ freeTimeSlots ; } return $ baseTimeSlots ; }

Create an array of non overlapped time slots

@param TimeSlotInterface          $baseTimeSlot
@param TimeSlotInterface[]        $overlappingTimeSlots
@param TimeSlotGeneratorInterface $timeSlotGenerator

@return TimeSlotInterface[]


public function mergeOverlappedTimeSlots(TimeSlotGeneratorInterface $timeSlotGenerator, array $timeSlots)
    {
        if (empty($timeSlots)) {
            return [];
        }

        $timeSlots = $this->sortTimeSlotsByStartTime($timeSlots);
        $mergedTimeSlots = [
            $timeSlotGenerator->createTimeSlot($timeSlots[0]->getStart(), $timeSlots[0]->getEnd()),
        ];
        $headIndex = 0;

        foreach ($timeSlots as $timeSlot) {
            $headTimeSlot = $mergedTimeSlots[$headIndex];

            if ($timeSlot->getStart() > $headTimeSlot->getEnd()) {
                $mergedTimeSlots[] = $timeSlotGenerator->createTimeSlot(
                    $timeSlot->getStart(),
                    $timeSlot->getEnd()
                );
                $headIndex ++;
            } elseif ($headTimeSlot->getEnd() < $timeSlot->getEnd()) {
                $mergedTimeSlots[$headIndex] = $timeSlotGenerator->createTimeSlot(
                    $headTimeSlot->getStart(),
                    $timeSlot->getEnd()
                );
            }
        }

        return $mergedTimeSlots;
    }

public function mergeOverlappedTimeSlots ( TimeSlotGeneratorInterface $ timeSlotGenerator , array $ timeSlots ) { if ( empty ( $ timeSlots ) ) { return [ ] ; } $ timeSlots = $ this -> sortTimeSlotsByStartTime ( $ timeSlots ) ; $ mergedTimeSlots = [ $ timeSlotGenerator -> createTimeSlot ( $ timeSlots [ 0 ] -> getStart ( ) , $ timeSlots [ 0 ] -> getEnd ( ) ) , ] ; $ headIndex = 0 ; foreach ( $ timeSlots as $ timeSlot ) { $ headTimeSlot = $ mergedTimeSlots [ $ headIndex ] ; if ( $ timeSlot -> getStart ( ) > $ headTimeSlot -> getEnd ( ) ) { $ mergedTimeSlots [ ] = $ timeSlotGenerator -> createTimeSlot ( $ timeSlot -> getStart ( ) , $ timeSlot -> getEnd ( ) ) ; $ headIndex ++ ; } elseif ( $ headTimeSlot -> getEnd ( ) < $ timeSlot -> getEnd ( ) ) { $ mergedTimeSlots [ $ headIndex ] = $ timeSlotGenerator -> createTimeSlot ( $ headTimeSlot -> getStart ( ) , $ timeSlot -> getEnd ( ) ) ; } } return $ mergedTimeSlots ; }

Merge all overlapped time slots into single time slot

@param TimeSlotGeneratorInterface $timeSlotGenerator
@param TimeSlotInterface[]        $timeSlots

@return TimeSlotInterface[]


public function get(string $path, array $parameters = [])
    {
        $requestUrl = $this->baseUrl . $path;
        try {
            return $this->executeRequest('GET', $requestUrl, $parameters);
        } catch (ClientException $e) {
            $response = $e->getResponse();
            if (null !== $response && 404 === $response->getStatusCode()) {
                return null;
            }
            throw new RestClientException(
                'Error while getting resource',
                $path,
                [],
                7,
                $e
            );
        } catch (TransferException $e) {
            throw new RestException(
                'Error while getting resource',
                $path,
                [],
                1,
                $e
            );
        }
    }

public
function
get
(
string
$
path
,
array
$
parameters
=
[
]
)
{
$
requestUrl
=
$
this
->
baseUrl
.
$
path
;
try
{
return
$
this
->
executeRequest
(
'GET'
,
$
requestUrl
,
$
parameters
)
;
}
catch
(
ClientException
$
e
)
{
$
response
=
$
e
->
getResponse
(
)
;
if
(
!==
$
response
&&
404
===
$
response
->
getStatusCode
(
)
)
{
return
;
}
throw
new
RestClientException
(
'Error while getting resource'
,
$
path
,
[
]
,
7
,
$
e
)
;
}
catch
(
TransferException
$
e
)
{
throw
new
RestException
(
'Error while getting resource'
,
$
path
,
[
]
,
1
,
$
e
)
;
}
}

get a path

@return array|ResponseInterface|null

@throws RestException


protected function mergeDefaultParameters(array $parameters): array
    {
        $request = $this->getCurrentRequest();

        $defaultParameters = ['version' => '1.0'];
        $defaultParameters['headers'] = ['Referer' => $request->getUri()];

        return array_replace_recursive($defaultParameters, $parameters);
    }

protected function mergeDefaultParameters ( array $ parameters ) : array { $ request = $ this -> getCurrentRequest ( ) ; $ defaultParameters = [ 'version' => '1.0' ] ; $ defaultParameters [ 'headers' ] = [ 'Referer' => $ request -> getUri ( ) ] ; return array_replace_recursive ( $ defaultParameters , $ parameters ) ; }


private function executeRequest(
        string $method,
        string $url,
        array $parameters = []
    ) {
        $parameters = $this->mergeDefaultParameters($parameters);

        $startTime = null;
        if ($this->isHistoryLogged()) {
            $startTime = microtime(true);
        }

        try {
            $response = $this->httpClient->request($method, $url, $parameters);
            $this->logRequest(
                $startTime,
                $method,
                $url,
                $parameters,
                $response
            );
        } catch (RequestException $e) {
            $this->logRequest(
                $startTime,
                $method,
                $url,
                $parameters,
                $e->getResponse()
            );
            throw $e;
        } catch (TransferException $e) {
            $this->logRequest($startTime, $method, $url, $parameters);
            throw $e;
        }

        $headers = $response->getHeaders();
        $jsonContentTypeList = ['application/ld+json', 'application/json'];

        $requestIsJson = false;

        if (isset($headers['Content-Type'])) {
            foreach ($jsonContentTypeList as $contentType) {
                if (
                    false !==
                    mb_stripos($headers['Content-Type'][0], $contentType)
                ) {
                    $requestIsJson = true;
                    break;
                }
            }
        }

        if ($requestIsJson) {
            return json_decode((string) $response->getBody(), true);
        } else {
            return $response;
        }
    }

private function executeRequest ( string $ method , string $ url , array $ parameters = [ ] ) { $ parameters = $ this -> mergeDefaultParameters ( $ parameters ) ; $ startTime = null ; if ( $ this -> isHistoryLogged ( ) ) { $ startTime = microtime ( true ) ; } try { $ response = $ this -> httpClient -> request ( $ method , $ url , $ parameters ) ; $ this -> logRequest ( $ startTime , $ method , $ url , $ parameters , $ response ) ; } catch ( RequestException $ e ) { $ this -> logRequest ( $ startTime , $ method , $ url , $ parameters , $ e -> getResponse ( ) ) ; throw $ e ; } catch ( TransferException $ e ) { $ this -> logRequest ( $ startTime , $ method , $ url , $ parameters ) ; throw $ e ; } $ headers = $ response -> getHeaders ( ) ; $ jsonContentTypeList = [ 'application/ld+json' , 'application/json' ] ; $ requestIsJson = false ; if ( isset ( $ headers [ 'Content-Type' ] ) ) { foreach ( $ jsonContentTypeList as $ contentType ) { if ( false !== mb_stripos ( $ headers [ 'Content-Type' ] [ 0 ] , $ contentType ) ) { $ requestIsJson = true ; break ; } } } if ( $ requestIsJson ) { return json_decode ( ( string ) $ response -> getBody ( ) , true ) ; } else { return $ response ; } }

Executes request.

@return ResponseInterface|array

@throws TransferException


protected function renderBackendView($start, NavigationIterator $iterator = null): string
    {
        $parent = $this->getParent();

        return $this->render(
            new ToolkitTemplateReference(
                'be_bs_tab',
                'html5',
                ToolkitTemplateReference::SCOPE_BACKEND
            ),
            [
                'name'  => $parent ? $parent->bs_tab_name : null,
                'color' => $start ? $this->rotateColor('ce:' . $start->id) : null,
                'error' => $start ? null : $this->translator->trans('ERR.bsTabParentMissing', [], 'contao_default'),
                'title' => $iterator ? $iterator->currentTitle() : null,
            ]
        );
    }

protected function renderBackendView ( $ start , NavigationIterator $ iterator = null ) : string { $ parent = $ this -> getParent ( ) ; return $ this -> render ( new ToolkitTemplateReference ( 'be_bs_tab' , 'html5' , ToolkitTemplateReference :: SCOPE_BACKEND ) , [ 'name' => $ parent ? $ parent -> bs_tab_name : null , 'color' => $ start ? $ this -> rotateColor ( 'ce:' . $ start -> id ) : null , 'error' => $ start ? null : $ this -> translator -> trans ( 'ERR.bsTabParentMissing' , [ ] , 'contao_default' ) , 'title' => $ iterator ? $ iterator -> currentTitle ( ) : null , ] ) ; }

Render the backend view.

@param ContentModel|null  $start    Start element.
@param NavigationIterator $iterator Iterator.

@return string


protected function getIterator(): ?NavigationIterator
    {
        $parent = $this->getParent();

        if (!$parent) {
            return null;
        }

        try {
            return $this->getTabRegistry()->getIterator((string) $parent->id);
        } catch (AssertionFailedException $e) {
            return null;
        }
    }

protected function getIterator ( ) : ? NavigationIterator { $ parent = $ this -> getParent ( ) ; if ( ! $ parent ) { return null ; } try { return $ this -> getTabRegistry ( ) -> getIterator ( ( string ) $ parent -> id ) ; } catch ( AssertionFailedException $ e ) { return null ; } }

Get the tab navigation iterator.

@return NavigationIterator


protected function getGridIterator(): ?GridIterator
    {
        $parent = $this->getParent();

        if (!$parent || !$this->gridProvider || !$parent->bs_grid) {
            return null;
        }

        try {
            $gridIterator = $this->gridProvider->getIterator('ce:' . $parent->id, (int) $parent->bs_grid);

            return $gridIterator;
        } catch (\RuntimeException $e) {
            return null;
        }
    }

protected function getGridIterator ( ) : ? GridIterator { $ parent = $ this -> getParent ( ) ; if ( ! $ parent || ! $ this -> gridProvider || ! $ parent -> bs_grid ) { return null ; } try { $ gridIterator = $ this -> gridProvider -> getIterator ( 'ce:' . $ parent -> id , ( int ) $ parent -> bs_grid ) ; return $ gridIterator ; } catch ( \ RuntimeException $ e ) { return null ; } }

Get the grid iterator.

@return GridIterator|null


public function beforeSave($event)
    {
        $content = $this->owner->{$this->attribute};

        if ($this->enableHtmlPurifierBefore) {
            $content = HtmlPurifier::process($content, $this->configHtmlPurifierBefore);
        }

        $content = $this->process($content);

        if ($this->enableHtmlPurifierAfter) {
            $content = HtmlPurifier::process($content, $this->configHtmlPurifierAfter);
        }

        $this->owner->{$this->saveAttribute} = $content;
    }

public function beforeSave ( $ event ) { $ content = $ this -> owner -> { $ this -> attribute } ; if ( $ this -> enableHtmlPurifierBefore ) { $ content = HtmlPurifier :: process ( $ content , $ this -> configHtmlPurifierBefore ) ; } $ content = $ this -> process ( $ content ) ; if ( $ this -> enableHtmlPurifierAfter ) { $ content = HtmlPurifier :: process ( $ content , $ this -> configHtmlPurifierAfter ) ; } $ this -> owner -> { $ this -> saveAttribute } = $ content ; }

Parsing BB-codes before save of model.

@param \yii\base\Event $event

Parsing BB - codes before save of model .


protected function process($content)
    {
        $parser = new Parser();

        $parser->addCodeDefinitionSet(new $this->defaultCodeDefinitionSet());

        // add definitions builder
        foreach ($this->codeDefinitionBuilder as $item) {
            if (is_string($item)) {
                $builder = new $item;
                if ($builder instanceof CodeDefinitionBuilder) {
                    $parser->addCodeDefinition($builder->build());
                }
            } elseif ($item instanceof CodeDefinitionBuilder) {
                $parser->addCodeDefinition($item->build());
            } elseif (is_callable($item)) {
                $parser->addCodeDefinition(call_user_func_array($item, [new CodeDefinitionBuilder('', '')]));
            } elseif (isset($item[0]) && isset($item[1])) {
                $builder = new CodeDefinitionBuilder($item[0], $item[1]);
                $parser->addCodeDefinition($builder->build());
            }
        }
        //added definitions set
        foreach ($this->codeDefinitionSet as $item) {
            if (is_string($item)) {
                $set = new $item;
                if ($set instanceof CodeDefinitionSet) {
                    $parser->addCodeDefinitionSet($set);
                }
            } elseif ($item instanceof CodeDefinitionSet) {
                $parser->addCodeDefinitionSet($item);
            }
        }
        //added definitions
        foreach ($this->codeDefinition as $item) {
            if (is_string($item)) {
                $set = new $item;
                if ($set instanceof CodeDefinition) {
                    $parser->addCodeDefinition($set);
                }
            } elseif ($item instanceof CodeDefinition) {
                $parser->addCodeDefinition($item);
            }
        }

        $parser->parse($content);

        if ($this->asHtml) {
            return $parser->getAsHtml();
        }
        return $parser->getAsBBCode();
    }

protected
function
process
(
$
content
)
{
$
parser
=
new
Parser
(
)
;
$
parser
->
addCodeDefinitionSet
(
new
$
this
->
defaultCodeDefinitionSet
(
)
)
;
// add definitions builder
foreach
(
$
this
->
codeDefinitionBuilder
as
$
item
)
{
if
(
is_string
(
$
item
)
)
{
$
builder
=
new
$
item
;
if
(
$
builder
instanceof
CodeDefinitionBuilder
)
{
$
parser
->
addCodeDefinition
(
$
builder
->
build
(
)
)
;
}
}
elseif
(
$
item
instanceof
CodeDefinitionBuilder
)
{
$
parser
->
addCodeDefinition
(
$
item
->
build
(
)
)
;
}
elseif
(
is_callable
(
$
item
)
)
{
$
parser
->
addCodeDefinition
(
call_user_func_array
(
$
item
,
[
new
CodeDefinitionBuilder
(
''
,
''
)
]
)
)
;
}
elseif
(
isset
(
$
item
[
0
]
)
&&
isset
(
$
item
[
1
]
)
)
{
$
builder
=
new
CodeDefinitionBuilder
(
$
item
[
0
]
,
$
item
[
1
]
)
;
$
parser
->
addCodeDefinition
(
$
builder
->
build
(
)
)
;
}
}
//added definitions set
foreach
(
$
this
->
codeDefinitionSet
as
$
item
)
{
if
(
is_string
(
$
item
)
)
{
$
set
=
new
$
item
;
if
(
$
set
instanceof
CodeDefinitionSet
)
{
$
parser
->
addCodeDefinitionSet
(
$
set
)
;
}
}
elseif
(
$
item
instanceof
CodeDefinitionSet
)
{
$
parser
->
addCodeDefinitionSet
(
$
item
)
;
}
}
//added definitions
foreach
(
$
this
->
codeDefinition
as
$
item
)
{
if
(
is_string
(
$
item
)
)
{
$
set
=
new
$
item
;
if
(
$
set
instanceof
CodeDefinition
)
{
$
parser
->
addCodeDefinition
(
$
set
)
;
}
}
elseif
(
$
item
instanceof
CodeDefinition
)
{
$
parser
->
addCodeDefinition
(
$
item
)
;
}
}
$
parser
->
parse
(
$
content
)
;
if
(
$
this
->
asHtml
)
{
return
$
parser
->
getAsHtml
(
)
;
}
return
$
parser
->
getAsBBCode
(
)
;
}

Parsing of BB-codes.

@param string $content Content for parsing.
@return string


public function actionUpdate($id)
    {
        $module = MediaModule::getInstance();
        if (!is_null($module->adminLayout)) {
            $this->layout = $module->adminLayout;
        }

        $model = $this->findModel($id);
        $model->title = $model->id;
        $controllerName = $this->getUniqueId();

        $meta['title'] = $this->pageTitle;
        $meta['description'] = 'Update media';
        $meta['pageIcon'] = $this->pageIcon;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Media has been updated');
            return $this->redirect(Url::previous());
        } else {
            return $this->render('update', [
                'model' => $model,
                'meta' => $meta,
                'controllerName' => $controllerName,
            ]);
        }
    }

public
function
actionUpdate
(
$
id
)
{
$
module
=
MediaModule
::
getInstance
(
)
;
if
(
!
is_null
(
$
module
->
adminLayout
)
)
{
$
this
->
layout
=
$
module
->
adminLayout
;
}
$
model
=
$
this
->
findModel
(
$
id
)
;
$
model
->
title
=
$
model
->
id
;
$
controllerName
=
$
this
->
getUniqueId
(
)
;
$
meta
[
'title'
]
=
$
this
->
pageTitle
;
$
meta
[
'description'
]
=
'Update media'
;
$
meta
[
'pageIcon'
]
=
$
this
->
pageIcon
;
if
(
$
model
->
load
(
Yii
::
$
app
->
request
->
post
(
)
)
&&
$
model
->
save
(
)
)
{
Yii
::
$
app
->
session
->
setFlash
(
'success'
,
'Media has been updated'
)
;
return
$
this
->
redirect
(
Url
::
previous
(
)
)
;
}
else
{
return
$
this
->
render
(
'update'
,
[
'model'
=>
$
model
,
'meta'
=>
$
meta
,
'controllerName'
=>
$
controllerName
,
]
)
;
}
}

Updates an existing Media model.
If update is successful, the browser will be redirected to the 'view' page.
@param string $id
@return mixed

Updates an existing Media model . If update is successful the browser will be redirected to the view page .


private function doMediaJoin($result)
    {
        if (isset($_GET['content_id']) && isset($_GET['content_type'])) {
            $media = $result['data'];
            if (!is_null($media)) {
                //Do join here
                $contentMedia = new ContentMedia();
                $contentMedia->content_id = $_GET['content_id'];
                $contentMedia->content_type = $_GET['content_type'];
                $contentMedia->media_id = $media['id'];
                if ($contentMedia->save(false)) {
                    //success
                    return true;
                } else {
                    return false;
                }
            }
        }

        return true;
    }

private
function
doMediaJoin
(
$
result
)
{
if
(
isset
(
$
_GET
[
'content_id'
]
)
&&
isset
(
$
_GET
[
'content_type'
]
)
)
{
$
media
=
$
result
[
'data'
]
;
if
(
!
is_null
(
$
media
)
)
{
//Do join here
$
contentMedia
=
new
ContentMedia
(
)
;
$
contentMedia
->
content_id
=
$
_GET
[
'content_id'
]
;
$
contentMedia
->
content_type
=
$
_GET
[
'content_type'
]
;
$
contentMedia
->
media_id
=
$
media
[
'id'
]
;
if
(
$
contentMedia
->
save
(
false
)
)
{
//success
return
true
;
}
else
{
return
false
;
}
}
}
return
true
;
}

If content id and type provided then do join
return boolean
@param $result
@return bool


public function actionUpload()
    {
        /**
         * @var \kato\modules\media\Media $module
         */
        $module = \Yii::$app->controller->module;
        $result = $module->mediaUpload();

        $response = new Response();
        $response->format = Response::FORMAT_JSON;
        $response->setStatusCode(500);

        if ($result['success'] === true) {

            if ($this->doMediaJoin($result)) {
                //success
                $response->setStatusCode(200);
                $response->data = $result['data'];
                $response->send();
                Yii::$app->end();
            } else {
                $response->statusText = 'Unable to do join of media with content.';
                $response->send();
                Yii::$app->end();
            }

        } else {
            $response->statusText = $result['message'];
            $response->send();
            Yii::$app->end();
        }
    }


public function actionUpdateData($id)
    {
        if ($post = Yii::$app->request->post()) {
            $model = $this->findModel($id);
            $model->$post['name'] = $post['value'];
            if ($model->save(false)) {
                echo 'true';
                exit;
            }
        }
        echo 'false';
    }

public function actionUpdateData ( $ id ) { if ( $ post = Yii :: $ app -> request -> post ( ) ) { $ model = $ this -> findModel ( $ id ) ; $ model -> $ post [ 'name' ] = $ post [ 'value' ] ; if ( $ model -> save ( false ) ) { echo 'true' ; exit ; } } echo 'false' ; }

Update data information of media
@param $id
@throws NotFoundHttpException


public function actionListMedia()
    {
        $result = array();

        if (isset($_GET['content_id']) && isset($_GET['content_type'])) {
            //get for modal
            $media = Media::find()
                ->leftJoin('kato_content_media', 'kato_content_media.media_id = kato_media.id')
                ->where(['kato_content_media.content_id' => $_GET['content_id'], 'kato_content_media.content_type' => $_GET['content_type']])
                ->all();
        } else {
            //return all media
            $media = Media::find()->all();
        }

        if ($media) {
            foreach ($media as $data) {
                $result[] = array(
                    'thumb' => '/' . $data->source,
                    'image' => '/' . $data->source,
                    'title' => '/' . $data->filename,
                    //'filelink' => '/' . $data->source,
                );
            }
        }

        echo Json::encode($result);
    }


public function actionRenderRow($id)
    {
        $this->layout = false;

        if ($media = $this->findModel($id)) {
            return $this->render('mediaRow', [
                'media' => $media,
                'isNew' => true,
            ]);
        }
        return '';
    }

public function actionRenderRow ( $ id ) { $ this -> layout = false ; if ( $ media = $ this -> findModel ( $ id ) ) { return $ this -> render ( 'mediaRow' , [ 'media' => $ media , 'isNew' => true , ] ) ; } return '' ; }

Get data about requested media and return as row
@param $id
@return string
@throws NotFoundHttpException


public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        if (Yii::$app->request->isAjax) {
            echo 'true';
            exit;
        }

        Yii::$app->session->setFlash('success', 'Media has been deleted');

        return $this->redirect(Url::previous());
    }

public
function
actionDelete
(
$
id
)
{
$
this
->
findModel
(
$
id
)
->
delete
(
)
;
if
(
Yii
::
$
app
->
request
->
isAjax
)
{
echo
'true'
;
exit
;
}
Yii
::
$
app
->
session
->
setFlash
(
'success'
,
'Media has been deleted'
)
;
return
$
this
->
redirect
(
Url
::
previous
(
)
)
;
}

Deletes an existing Media model.
If deletion is successful, the browser will be redirected to the 'index' page.
@param integer $id
@return mixed

Deletes an existing Media model . If deletion is successful the browser will be redirected to the index page .


public function setAttributeList($attributeList): self
    {
        $this->attributeList = [];

        foreach ($attributeList as $attribute) {
            $this->attributeList[$attribute->getSerializedKey()] = $attribute;

            if ($attribute->isIdentifier()) {
                if ($this->identifierAttribute) {
                    throw new MoreThanOneIdentifierException(
                        sprintf(
                            'Class metadata for model "%s" already has an identifier named "%s". Only one identifier is allowed.',
                            $this->modelName,
                            $this->identifierAttribute->getSerializedKey()
                        )
                    );
                }

                $this->identifierAttribute = $attribute;
            }
        }

        return $this;
    }

Setter for attributeList

@param  iterable<Attribute> $attributeList


public function getDefaultSerializedModel(): array
    {
        $out = [];
        $attributeList = $this->getAttributeList();
        if ($attributeList) {
            foreach ($attributeList as $attribute) {
                $out[$attribute->getSerializedKey()] = null;
            }
        }

        $relationList = $this->getRelationList();
        if ($relationList) {
            foreach ($relationList as $relation) {
                if ($relation->isOneToMany()) {
                    $out[$relation->getSerializedKey()] = [];
                }
            }
        }

        return $out;
    }

public function getDefaultSerializedModel ( ) : array { $ out = [ ] ; $ attributeList = $ this -> getAttributeList ( ) ; if ( $ attributeList ) { foreach ( $ attributeList as $ attribute ) { $ out [ $ attribute -> getSerializedKey ( ) ] = null ; } } $ relationList = $ this -> getRelationList ( ) ; if ( $ relationList ) { foreach ( $ relationList as $ relation ) { if ( $ relation -> isOneToMany ( ) ) { $ out [ $ relation -> getSerializedKey ( ) ] = [ ] ; } } } return $ out ; }

return default serialize model with null value or empty array on relations

@return array<string, array|null>


protected function createDirectories()
    {
        if (! is_dir(base_path('resources/views/layouts'))) {
            mkdir(base_path('resources/views/layouts'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/emails'))) {
            mkdir(base_path('resources/views/emails'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/errors'))) {
            mkdir(base_path('resources/views/errors'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/partials'))) {
            mkdir(base_path('resources/views/partials'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/profile'))) {
            mkdir(base_path('resources/views/profile'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/profile/partials'))) {
            mkdir(base_path('resources/views/profile/partials'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/users'))) {
            mkdir(base_path('resources/views/users'), 0755, true);
        }

        if (! is_dir(base_path('resources/views/auth/passwords'))) {
            mkdir(base_path('resources/views/auth/passwords'), 0755, true);
        }

        if (! is_dir(public_path('plugins'))) {
            mkdir(public_path('plugins'), 0755, true);
        }

        if (! is_dir(base_path('resources/assets/less'))) {
            mkdir(base_path('resources/assets/less'), 0755, true);
        }

        if (! is_dir(base_path('resources/assets/js'))) {
            mkdir(base_path('resources/assets/js'), 0755, true);
        }
    }

protected function createDirectories ( ) { if ( ! is_dir ( base_path ( 'resources/views/layouts' ) ) ) { mkdir ( base_path ( 'resources/views/layouts' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/emails' ) ) ) { mkdir ( base_path ( 'resources/views/emails' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/errors' ) ) ) { mkdir ( base_path ( 'resources/views/errors' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/partials' ) ) ) { mkdir ( base_path ( 'resources/views/partials' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/profile' ) ) ) { mkdir ( base_path ( 'resources/views/profile' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/profile/partials' ) ) ) { mkdir ( base_path ( 'resources/views/profile/partials' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/users' ) ) ) { mkdir ( base_path ( 'resources/views/users' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/views/auth/passwords' ) ) ) { mkdir ( base_path ( 'resources/views/auth/passwords' ) , 0755 , true ) ; } if ( ! is_dir ( public_path ( 'plugins' ) ) ) { mkdir ( public_path ( 'plugins' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/assets/less' ) ) ) { mkdir ( base_path ( 'resources/assets/less' ) , 0755 , true ) ; } if ( ! is_dir ( base_path ( 'resources/assets/js' ) ) ) { mkdir ( base_path ( 'resources/assets/js' ) , 0755 , true ) ; } }

Create the directories for the files.

@return void


protected function exportViews()
    {
        foreach ($this->views as $key => $value) {
            $path = base_path('resources/views/'.$value);

            $this->line('<info>View:</info> '.$path);

            try {
                copy(__DIR__ . '/../stubs/views/' . $key, $path);
            } catch (ErrorException $e) {
                $this->error(__DIR__ . '/../stubs/views/' . $key);
                $this->error($path);
            }
        }
    }

protected
function
exportViews
(
)
{
foreach
(
$
this
->
views
as
$
key
=>
$
value
)
{
$
path
=
base_path
(
'resources/views/'
.
$
value
)
;
$
this
->
line
(
'<info>View:</info> '
.
$
path
)
;
try
{
copy
(
__DIR__
.
'/../stubs/views/'
.
$
key
,
$
path
)
;
}
catch
(
ErrorException
$
e
)
{
$
this
->
error
(
__DIR__
.
'/../stubs/views/'
.
$
key
)
;
$
this
->
error
(
$
path
)
;
}
}
}


protected function exportControllers()
    {
        foreach ($this->controllers as $key => $value) {

            $path = app_path('Http/Controllers/'.$value);

            $this->line('<info>Controller:</info> '.$path);

            file_put_contents(
                app_path('Http/Controllers/'.$value),
                $this->compileControllerStub($key)
            );
        }
    }

protected
function
exportControllers
(
)
{
foreach
(
$
this
->
controllers
as
$
key
=>
$
value
)
{
$
path
=
app_path
(
'Http/Controllers/'
.
$
value
)
;
$
this
->
line
(
'<info>Controller:</info> '
.
$
path
)
;
file_put_contents
(
app_path
(
'Http/Controllers/'
.
$
value
)
,
$
this
->
compileControllerStub
(
$
key
)
)
;
}
}


protected function exportRoutes()
    {
        if ($this->version < 5.3) {
            $routeFile = app_path('Http/routes.php');
            $stubFile = __DIR__.'/../stubs/routes.stub';
        }
        else {
            $routeFile = base_path('routes/web.php');
            $stubFile = __DIR__.'/../stubs/routes/web.stub';
        }

        $routeContent = file_get_contents($routeFile);

        preg_match('/ProfileController@view/', $routeContent, $matches);

        if (! count($matches)) {
            $this->info('Updated Routes File.');

            file_put_contents(
                $routeFile,
                file_get_contents($stubFile),
                FILE_APPEND
            );
        }
    }

protected
function
exportRoutes
(
)
{
if
(
$
this
->
version
<
5.3
)
{
$
routeFile
=
app_path
(
'Http/routes.php'
)
;
$
stubFile
=
__DIR__
.
'/../stubs/routes.stub'
;
}
else
{
$
routeFile
=
base_path
(
'routes/web.php'
)
;
$
stubFile
=
__DIR__
.
'/../stubs/routes/web.stub'
;
}
$
routeContent
=
file_get_contents
(
$
routeFile
)
;
preg_match
(
'/ProfileController@view/'
,
$
routeContent
,
$
matches
)
;
if
(
!
count
(
$
matches
)
)
{
$
this
->
info
(
'Updated Routes File.'
)
;
file_put_contents
(
$
routeFile
,
file_get_contents
(
$
stubFile
)
,
FILE_APPEND
)
;
}
}


protected function checkPackages()
    {
        if (! is_dir(base_path('vendor/twbs'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>Bootstrap</comment> package!');
            $this->line('Run: <comment>composer require twbs/bootstrap</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('vendor/almasaeed2010'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>AdminLTE</comment> package!');
            $this->line('Run: <comment>composer require almasaeed2010/adminlte</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/jquery'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>jQuery</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install jquery</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/font-awesome'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>Font Awesome</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install font-awesome</comment>'."\n");
            return false;
        }

        if (! is_dir(base_path('node_modules/ionicons'))) {
            $this->line('');
            $this->line('<error> Error </error> Missing <comment>IonIcons</comment> package!');
            $this->line('Run: <comment>npm install</comment> or <comment>npm install ionicons</comment>'."\n");
            return false;
        }

        return true;
    }

Check all required packages

@return bool


protected function copyPlugins()
    {
        $destination = public_path('plugins');

        $this->line('<info>Plugin:</info> ' . $destination);
        File::copyDirectory(base_path('vendor/almasaeed2010/adminlte/plugins'), $destination);
    }

protected
function
copyPlugins
(
)
{
$
destination
=
public_path
(
'plugins'
)
;
$
this
->
line
(
'<info>Plugin:</info> '
.
$
destination
)
;
File
::
copyDirectory
(
base_path
(
'vendor/almasaeed2010/adminlte/plugins'
)
,
$
destination
)
;
}

Copy jQuery plugins folder from AdminLTE package


protected function copyAssetFiles()
    {
        foreach ($this->assets as $destination => $source) {

            $this->line('<info>Asset:</info> ' . base_path($destination));

            file_put_contents(
                base_path($destination),
                file_get_contents($source)
            );
        }
    }

protected
function
copyAssetFiles
(
)
{
foreach
(
$
this
->
assets
as
$
destination
=>
$
source
)
{
$
this
->
line
(
'<info>Asset:</info> '
.
base_path
(
$
destination
)
)
;
file_put_contents
(
base_path
(
$
destination
)
,
file_get_contents
(
$
source
)
)
;
}
}


protected function copyLessFolders()
    {
        foreach ($this->lessSources as $source => $destination) {

            $this->line('<info>LESS:</info> ' . base_path($destination));

            File::copyDirectory(
                base_path($source),
                base_path($destination)
            );
        }
    }

protected
function
copyLessFolders
(
)
{
foreach
(
$
this
->
lessSources
as
$
source
=>
$
destination
)
{
$
this
->
line
(
'<info>LESS:</info> '
.
base_path
(
$
destination
)
)
;
File
::
copyDirectory
(
base_path
(
$
source
)
,
base_path
(
$
destination
)
)
;
}
}


public function getByCategories()
    {
        $data = [
            'categories' => $this->getCategories(),
            'settings' => [],
        ];

        foreach ($data['categories'] as $key => $category) {
            $model = self::find()
                ->where(['category' => $category])
                ->indexBy('id')
                ->all();
            $data['settings'][$category] = $model;
        }

        return $data;
    }

public function getByCategories ( ) { $ data = [ 'categories' => $ this -> getCategories ( ) , 'settings' => [ ] , ] ; foreach ( $ data [ 'categories' ] as $ key => $ category ) { $ model = self :: find ( ) -> where ( [ 'category' => $ category ] ) -> indexBy ( 'id' ) -> all ( ) ; $ data [ 'settings' ] [ $ category ] = $ model ; } return $ data ; }

Returns settings grouped by categories
@return array


public static function fromSerialized(string $definition, string $tabId): self
    {
        $navigation = new Navigation();
        $current    = $navigation;
        $definition = StringUtil::deserialize($definition, true);
        $cssIds     = [];

        foreach ($definition as $index => $tab) {
            if (!$tab['cssId']) {
                $tab['cssId']  = StringUtil::standardize($tab['title']);
                $tab['cssId'] .= '-' . $tabId;

                if (in_array($tab['cssId'], $cssIds)) {
                    $tab['cssId'] .= '-' . $index;
                }
            }

            if ($tab['type'] === 'dropdown') {
                $item    = Dropdown::fromArray($tab);
                $current = $item;

                $navigation->addItem($item);
            } else {
                if ($tab['type'] !== 'child') {
                    $current = $navigation;
                }

                $item = NavItem::fromArray($tab);
                $current->addItem($item);
            }
        }

        return $navigation;
    }

public static function fromSerialized ( string $ definition , string $ tabId ) : self { $ navigation = new Navigation ( ) ; $ current = $ navigation ; $ definition = StringUtil :: deserialize ( $ definition , true ) ; $ cssIds = [ ] ; foreach ( $ definition as $ index => $ tab ) { if ( ! $ tab [ 'cssId' ] ) { $ tab [ 'cssId' ] = StringUtil :: standardize ( $ tab [ 'title' ] ) ; $ tab [ 'cssId' ] .= '-' . $ tabId ; if ( in_array ( $ tab [ 'cssId' ] , $ cssIds ) ) { $ tab [ 'cssId' ] .= '-' . $ index ; } } if ( $ tab [ 'type' ] === 'dropdown' ) { $ item = Dropdown :: fromArray ( $ tab ) ; $ current = $ item ; $ navigation -> addItem ( $ item ) ; } else { if ( $ tab [ 'type' ] !== 'child' ) { $ current = $ navigation ; } $ item = NavItem :: fromArray ( $ tab ) ; $ current -> addItem ( $ item ) ; } } return $ navigation ; }

Create instance from a serialized definition

@param string $definition Serialized definition.
@param string $tabId      Tab id as string, used as css id suffix.

@return Navigation


public static function fromArray(array $definition): NavItem
    {
        return new static(
            $definition['title'],
            (bool) $definition['active'],
            $definition['cssId'] ?? null,
            $definition['navCssId'] ?? null
        );
    }

public static function fromArray ( array $ definition ) : NavItem { return new static ( $ definition [ 'title' ] , ( bool ) $ definition [ 'active' ] , $ definition [ 'cssId' ] ?? null , $ definition [ 'navCssId' ] ?? null ) ; }

Create nav item from an array definition.

@param array $definition The array definition.

@return NavItem

Create nav item from an array definition .


public function loadBlock($name, $isGlobal = false)
    {
        if (is_null($name)) {
            throw new BadRequestHttpException('Block name not specified.');
        }

        $find = [
            'title' => $name,
        ];

        if ($isGlobal === false) {
            //if not global
            if (isset($this->params['block']['id'])) {
                $find['parent'] = $this->params['block']['id'];
            }
            if (isset($this->params['block']['layout'])) {
                $find['parent_layout'] = $this->params['block']['layout'];
            }

            if (isset($this->params['block']['slug'])) {
                //get parent page id
                /**
                 * @var $page \backend\models\Page
                 */
                if ($page = Page::findOne([
                    'slug' => $this->params['block']['slug'],
                ])) {
                    $find['parent'] = $page->id;
                }
            }
        }

        /**
         * @var $block \backend\models\Block
         */
        if ($block = Block::findOne($find)) {
            //if block found
            return $block->render();
        }

        return false;
    }

finds and return content of requested block by name
@param $name
@param bool $isGlobal
@return bool|string
@throws BadRequestHttpException


public function getModule($m)
    {
        $mod = Yii::$app->controller->module;
        return $mod && $mod->getModule($m) ? $mod->getModule($m) : Yii::$app->getModule($m);
    }

public function getModule ( $ m ) { $ mod = Yii :: $ app -> controller -> module ; return $ mod && $ mod -> getModule ( $ m ) ? $ mod -> getModule ( $ m ) : Yii :: $ app -> getModule ( $ m ) ; }

Gets the module
@param $m
@return null|\yii\base\Module


public function serialize(
        object $entity,
        string $modelName,
        array $context = []
    ): array {
        $out = $this->recursiveSerialize($entity, $modelName, 0, $context);

        if (is_string($out)) {
            throw new \RuntimeException(
                'recursiveSerialize should return an array for level 0 of serialization. This should not happen.'
            );
        }

        return $out;
    }


public function getModelName(string $key): string
    {
        $this->checkMappingExistence($key, true);

        /** @var ClassMetadata */
        $classMetadata = $this->getClassMetadataByKey($key);

        return $classMetadata->getModelName();
    }

public
function
getModelName
(
string
$
key
)
:
string
{
$
this
->
checkMappingExistence
(
$
key
,
true
)
;
/** @var ClassMetadata */
$
classMetadata
=
$
this
->
getClassMetadataByKey
(
$
key
)
;
return
$
classMetadata
->
getModelName
(
)
;
}

return a model class name for a given key


public function getClassMetadata(string $modelName): ClassMetadata
    {
        foreach ($this->classMetadataList as $classMetadata) {
            if ($modelName === $classMetadata->getModelName()) {
                return $classMetadata;
            }
        }

        throw new MappingException($modelName . ' model is not mapped');
    }

public
function
getClassMetadata
(
string
$
modelName
)
:
ClassMetadata
{
foreach
(
$
this
->
classMetadataList
as
$
classMetadata
)
{
if
(
$
modelName
===
$
classMetadata
->
getModelName
(
)
)
{
return
$
classMetadata
;
}
}
throw
new
MappingException
(
$
modelName
.
' model is not mapped'
)
;
}

getClassMetadata for model name

@throws MappingException


public function tryGetClassMetadataById(string $id): ?ClassMetadata
    {
        $key = $this->parseKeyFromId($id);

        foreach ($this->classMetadataList as $classMetadata) {
            if ($key === $classMetadata->getKey()) {
                return $classMetadata;
            }
        }

        return null;
    }

public function tryGetClassMetadataById ( string $ id ) : ? ClassMetadata { $ key = $ this -> parseKeyFromId ( $ id ) ; foreach ( $ this -> classMetadataList as $ classMetadata ) { if ( $ key === $ classMetadata -> getKey ( ) ) { return $ classMetadata ; } } return null ; }


private function renderTree($parentId = 0)
    {
        $query = Page::find();
        $query->andWhere(['deleted' => 0, 'revision_to' => 0, 'parent_id' => $parentId]);
        $query->orderBy('title ASC');

        if (($pages = $query->all()) == null) {
            //empty array if no data found
            return [];
        }

        $tree = $this->getBranch($pages, true);

        return $tree;
    }

private
function
renderTree
(
$
parentId
=
0
)
{
$
query
=
Page
::
find
(
)
;
$
query
->
andWhere
(
[
'deleted'
=>
0
,
'revision_to'
=>
0
,
'parent_id'
=>
$
parentId
]
)
;
$
query
->
orderBy
(
'title ASC'
)
;
if
(
(
$
pages
=
$
query
->
all
(
)
)
==
)
{
//empty array if no data found
return
[
]
;
}
$
tree
=
$
this
->
getBranch
(
$
pages
,
true
)
;
return
$
tree
;
}

Returns hierarchical data of pages
@param int $parentId
@return array


protected function getBranch($pages)
    {
        $result = [];

        foreach ($pages as $page) {
            $result[] = array('model' => $page, 'children' => $this->renderTree($page->id));
        }

        return $result;
    }

protected function getBranch ( $ pages ) { $ result = [ ] ; foreach ( $ pages as $ page ) { $ result [ ] = array ( 'model' => $ page , 'children' => $ this -> renderTree ( $ page -> id ) ) ; } return $ result ; }

Returns the given pages as a branch.
@param $pages
@return array


protected function removeFromCache(string $key): bool
    {
        $key = $this->normalizeCacheKey($key);
        $cacheItemPool = $this->sdk->getCacheItemPool();
        if ($cacheItemPool) {
            $cacheKey = $this->sdk->getCachePrefix() . $key;

            if ($cacheItemPool->hasItem($cacheKey)) {
                return $cacheItemPool->deleteItem($cacheKey);
            }
        }

        return true;
    }

protected function removeFromCache ( string $ key ) : bool { $ key = $ this -> normalizeCacheKey ( $ key ) ; $ cacheItemPool = $ this -> sdk -> getCacheItemPool ( ) ; if ( $ cacheItemPool ) { $ cacheKey = $ this -> sdk -> getCachePrefix ( ) . $ key ; if ( $ cacheItemPool -> hasItem ( $ cacheKey ) ) { return $ cacheItemPool -> deleteItem ( $ cacheKey ) ; } } return true ; }

remove from cache

@return bool true if no cache or cache successfully cleared, false otherwise


public static function listTags($tagType = null, $limit = 30)
    {
        $model = self::find()
            ->select('name')
            ->orderBy('frequency DESC, Name')
            ->limit($limit);
            if (!is_null($tagType)) {
                $data = $model->where('tag_type = :type', [':type' => $tagType])->all();
            } else {
                $data = $model->all();
            }

        $return = [''];
        if (!empty($data)) {
            foreach ($data as $tag) {
                $return[] = $tag->name;
            }
        }
        return $return;
    }

public
static
function
listTags
(
$
tagType
=
,
$
limit
=
30
)
{
$
model
=
self
::
find
(
)
->
select
(
'name'
)
->
orderBy
(
'frequency DESC, Name'
)
->
limit
(
$
limit
)
;
if
(
!
is_null
(
$
tagType
)
)
{
$
data
=
$
model
->
where
(
'tag_type = :type'
,
[
':type'
=>
$
tagType
]
)
->
all
(
)
;
}
else
{
$
data
=
$
model
->
all
(
)
;
}
$
return
=
[
''
]
;
if
(
!
empty
(
$
data
)
)
{
foreach
(
$
data
as
$
tag
)
{
$
return
[
]
=
$
tag
->
name
;
}
}
return
$
return
;
}

Returns array of tags by tag type
@param null $tagType
@param int $limit
@return array