public function onKernelResponse(FilterResponseEvent $event)
    {
        $config = [
            'id' => $this->params['number'],
            'accurateTrackBounce' => $this->params['accurateTrackBounce'], // показатель отказов: true | false | 10000 (ms)
            'clickmap' => $this->params['clickmap'], // Включает карту кликов
            'defer' => $this->params['defer'], // Не отправлять хит при инициализации счетчика
            'enableAll' => $this->params['enableAll'], // Включает отслеживание внешних ссылок, карту кликов и точный показатель отказов
            'onlyHttps' => $this->params['onlyHttps'], // true — данные в Метрику передаются только по https-протоколу;
            'params' => $this->params['params'], // Параметры, передаваемые вместе с хитом
            'trackHash' => true, // Включает отслеживание хеша в адресной строке браузера
            'trackLinks' => true, // Включает отслеживание внешних ссылок
            'type' => 0, // Тип счетчика. Для РСЯ равен 1
            'ut' => 0, // Запрет отправки страниц на индексацию http://help.yandex.ru/metrika/code/stop-indexing.xml#stop-indexing
            'webvisor' => true, // Включает Вебвизор
        ];

        $htmlCode = $this->templating->render('keltanasYandexMetrikaBundle:Metrika:tracker.html.twig', [
                'ya_tracking' => $this->params['number'],
                'config' => array_filter($config),
                'debug' => $this->debug,
            ]);

        $event->getResponse()->setContent(str_replace(
            '',
            $htmlCode . '',
            $event->getResponse()->getContent()
        ));
    }

// Включает карту кликов

// Включает отслеживание внешних ссылок

// Тип счетчика. Для РСЯ равен 1

// Включает Вебвизор

Store value to cookie
@param FilterResponseEvent $event


public function getDefinitions()
    {
        $content = $this->loadFile($this->fileName);

        // empty file
        if (null === $content) {
            return [];
        }

        // imports
        $definitions = $this->parseImports($content);

        // parameters
        if (isset($content['parameters'])) {
            if (!is_array($content['parameters'])) {
                throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
            }

            foreach ($content['parameters'] as $key => $value) {
                $definitions[$key] = new ParameterDefinition($value);
                //$this->container->setParameter($key, $this->resolveServices($value));
            }
        }

        // services
        $serviceDefinitions = $this->parseDefinitions($content);
        $definitions = $definitions + $serviceDefinitions;

        return $definitions;
    }

Returns the definition to register in the container.

@return DefinitionInterface[]

Returns the definition to register in the container .


private function parseImports($content)
    {
        if (!isset($content['imports'])) {
            return [];
        }

        if (!is_array($content['imports'])) {
            throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
        }

        $additionalDefinitions = [];

        foreach ($content['imports'] as $import) {
            if (!is_array($import)) {
                throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $this->fileName));
            }

            if (isset($import['ignore_errors'])) {
                throw new InvalidArgumentException(sprintf('The "ignore_errors" key is not supported in YamlDefinitionLoader. This is a Symfony specific syntax. Check your YAML syntax.', $this->fileName));
            }

            $importFileName = $import['resource'];

            if (strpos($importFileName, '/') !== 0) {
                $importFileName = dirname($this->fileName).'/'.$importFileName;
            }

            $yamlDefinitionLoader = new self($importFileName);
            $newDefinitions = $yamlDefinitionLoader->getDefinitions();

            $additionalDefinitions = $newDefinitions + $additionalDefinitions;
        }

        return $additionalDefinitions;
    }

Parses all imports.

@param array $content
@param $content

@return DefinitionInterface[]


private function parseDefinitions($content)
    {
        if (!isset($content['services'])) {
            return [];
        }

        if (!is_array($content['services'])) {
            throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $this->fileName));
        }

        $definitions = [];

        foreach ($content['services'] as $id => $service) {
            $definitions[$id] = $this->parseDefinition($id, $service);
        }

        return $definitions;
    }

Parses definitions.

@param array $content

@return DefinitionInterface[]


protected function loadFile($file)
    {
        if (!stream_is_local($file)) {
            throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
        }

        if (!is_readable($file)) {
            throw new FileNotFoundException(sprintf('The file "%s" does not exist or is not readable.', $file));
        }

        $yamlParser = new Parser();

        try {
            $configuration = $yamlParser->parse(file_get_contents($file));
        } catch (ParseException $e) {
            throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
        }

        return $this->validate($configuration, $file);
    }

Loads a YAML file.

@param string $file

@return array The file content

@throws InvalidArgumentException when the given file is not a local file or when it does not exist


private function resolveServices($value)
    {
        if (is_array($value)) {
            return array_map(array($this, 'resolveServices'), $value);
        } elseif (is_string($value) &&  0 === strpos($value, '@=')) {
            throw new InvalidArgumentException('Expressions (starting by "@=") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
        } elseif (is_string($value) &&  0 === strpos($value, '@')) {
            if (0 === strpos($value, '@@')) {
                return substr($value, 1);
            } elseif (0 === strpos($value, '@?')) {
                throw new InvalidArgumentException('Optional services (starting by "@?") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
            } else {
                $value = substr($value, 1);
                if ('=' === substr($value, -1)) {
                    throw new InvalidArgumentException('Non-strict services (ending with "=") are not supported by YamlDefinitionLoader. This is a Symfony specific feature.');
                } else {
                }

                return new Reference($value);
            }
        } else {
            return $value;
        }
    }

Resolves services.

@param string|array $value

@return array|string|Reference


public function init(Autoload $loader, $loads = []){
        $this->loader = $loader;
        foreach ($loads['namespaces'] as $prefix => $namespace) {
            $this->loader->addNamespace($prefix, ROOT . DIRECTORY_SEPARATOR . ltrim($namespace, '/'));
        }
        foreach ($loads['classes'] as $class => $path) {
            $this->loader->addClass($class, ROOT . DIRECTORY_SEPARATOR . ltrim($path, '/'));
        }
        $this->loader->register();
    }

public function init ( Autoload $ loader , $ loads = [ ] ) { $ this -> loader = $ loader ; foreach ( $ loads [ 'namespaces' ] as $ prefix => $ namespace ) { $ this -> loader -> addNamespace ( $ prefix , ROOT . DIRECTORY_SEPARATOR . ltrim ( $ namespace , '/' ) ) ; } foreach ( $ loads [ 'classes' ] as $ class => $ path ) { $ this -> loader -> addClass ( $ class , ROOT . DIRECTORY_SEPARATOR . ltrim ( $ path , '/' ) ) ; } $ this -> loader -> register ( ) ; }

AutoloadProvider constructor.
@param Autoload $loader
@param array $loads


public function getApi()
    {
        if (is_null($this->api)) {
            $this->api = new AES();
            $this->api->setKey($this->getKey());
        }

        return $this->api;
    }

public function getApi ( ) { if ( is_null ( $ this -> api ) ) { $ this -> api = new AES ( ) ; $ this -> api -> setKey ( $ this -> getKey ( ) ) ; } return $ this -> api ; }

Returns an instance of the Crypto library

@return Crypt_AES


public static function humanize($bytes, $base = 1024)
    {
        if (empty($bytes)) {
            return '0 B';
        }
        $class = min((int)log($bytes, $base), count(static::$siPrefix) - 1);

        return sprintf('%1.2F %s', $bytes / pow($base, $class), static::$siPrefix[$class]);
    }

public
static
function
humanize
(
$
bytes
,
$
base
=
1024
)
{
if
(
empty
(
$
bytes
)
)
{
return
'0 B'
;
}
$
class
=
min
(
(
int
)
log
(
$
bytes
,
$
base
)
,
count
(
static
::
$
siPrefix
)
1
)
;
return
sprintf
(
'%1.2F %s'
,
$
bytes
/
pow
(
$
base
,
$
class
)
,
static
::
$
siPrefix
[
$
class
]
)
;
}

Humanize the size bu add a Prefix

@param integer $bytes
@param integer $base

@return string Readable size


public function setBullet($str) {

        // store the bullet, if it is null..
        if (is_null($str)) {

            // store the default bullet
            $this->bullet = $this->defaultBullet;

        // something was sent in
        } else {

            // store it
            $this->bullet = $str;
        }

        return $this;
    }

public
function
setBullet
(
$
str
)
{
// store the bullet, if it is null..
if
(
is_null
(
$
str
)
)
{
// store the default bullet
$
this
->
bullet
=
$
this
->
defaultBullet
;
// something was sent in
}
else
{
// store it
$
this
->
bullet
=
$
str
;
}
return
$
this
;
}

Set the bullet string for lists

@param $str
@return $this


public function setColumnDefinition($columnIndex, Column $column) {

        // if the index is valid
        if ($columnIndex < $this->columnCount) {

            // copy the column information
            $this->columnDefinitions[$columnIndex] = clone $column;
        }

    }

public
function
setColumnDefinition
(
$
columnIndex
,
Column
$
column
)
{
// if the index is valid
if
(
$
columnIndex
<
$
this
->
columnCount
)
{
// copy the column information
$
this
->
columnDefinitions
[
$
columnIndex
]
=
clone
$
column
;
}
}

Set the column definition for one column

@param int $columnIndex
@param Column $column


protected function calcTotalWidth() {

        $totalWidth = 0;

        // go through all the widths
        for ($w=0; $w<count($this->columnDefinitions); ++$w) {

            // add the column's width
            $totalWidth += $this->columnDefinitions[$w]->getWidth();
        }

        // return the total
        return $totalWidth;

    }

protected
function
calcTotalWidth
(
)
{
$
totalWidth
=
0
;
// go through all the widths
for
(
$
w
=
0
;
$
w
<
count
(
$
this
->
columnDefinitions
)
;
++
$
w
)
{
// add the column's width
$
totalWidth
+=
$
this
->
columnDefinitions
[
$
w
]
->
getWidth
(
)
;
}
// return the total
return
$
totalWidth
;
}

Simply add up all the column widths
@return int


protected function hasHeader() {

        // go through the column definitions
        for ($i=0; $i<count($this->columnDefinitions); ++$i) {

            // if one column has header text
            if ($this->columnDefinitions[$i]->hasHeaderText()) {

                // then there is a header
                return true;
            }
        }

        // none of the columns had header text
        return false;
    }

protected
function
hasHeader
(
)
{
// go through the column definitions
for
(
$
i
=
0
;
$
i
<
count
(
$
this
->
columnDefinitions
)
;
++
$
i
)
{
// if one column has header text
if
(
$
this
->
columnDefinitions
[
$
i
]
->
hasHeaderText
(
)
)
{
// then there is a header
return
true
;
}
}
// none of the columns had header text
return
false
;
}

Whether there is at least one header defined in the column definitions
@return bool


protected function getHeaderText() {

        $headers = [];

        // go through the column definitions
        for ($i=0; $i<count($this->columnDefinitions); ++$i) {

            $next = $this->columnDefinitions[$i];

            // if one column has header text
            if ($this->columnDefinitions[$i]->hasHeaderText()) {

                // then there is a header
                $headers[] = $next->getHeaderText();

            // there is no header
            } else {

                // put in a blank placeholder
                $headers[] = "";
            }
        }

        // none of the columns had header text
        return $headers;
    }

protected
function
getHeaderText
(
)
{
$
headers
=
[
]
;
// go through the column definitions
for
(
$
i
=
0
;
$
i
<
count
(
$
this
->
columnDefinitions
)
;
++
$
i
)
{
$
next
=
$
this
->
columnDefinitions
[
$
i
]
;
// if one column has header text
if
(
$
this
->
columnDefinitions
[
$
i
]
->
hasHeaderText
(
)
)
{
// then there is a header
$
headers
[
]
=
$
next
->
getHeaderText
(
)
;
// there is no header
}
else
{
// put in a blank placeholder
$
headers
[
]
=
""
;
}
}
// none of the columns had header text
return
$
headers
;
}

Return an array of the header text found in the header definitions
@return string[]


protected function dataCheck(&$data) {

        // no need to go on, if there is no data
        if (count($data) < 1 || !is_array($data)) {

            // exit
            return false;
        }

        // first check that there are enough Column definitions for the data supplied
        for ($r=0; $r<count($data); ++$r) {

            $rowColumnCount = count($data[$r]);

            // if this row does not have enough columns, add them
            if ($rowColumnCount > $this->columnCount) {

                // add as many Columns as needed to handle this larger row
                for ($i=$this->columnCount; $i<$rowColumnCount; ++$i) {

                    // add one default column
                    $this->columnDefinitions[] = new Column();
                }

                // update the column count to reflect this new size
                $this->columnCount = $rowColumnCount;
            }
        }

        // now, pad any row that doesn't have enough data to fill the columns
        for ($r=0; $r<count($data); ++$r) {

            // if this row does not have enough columns, add them
            if (count($data[$r]) < $this->columnCount) {

                // pad the array with empty space to fill out any columns not there
                $data[$r] = array_pad($data[$r],$this->columnCount,"");

            }
        }

        // we got past the hurdles, data is good
        return true;

    }

Helper function to ensure the data is correct

@param array $data
@return bool


protected function calculateWidths($data) {

        // get the markup definition from the HTML object
        $markupDefinition = $this->clio->getMarkupDefinition();

        // go through and calculate any column widths that were not calculated
        for ($column = 0; $column < $this->columnCount; ++$column) {

            // get the column definition for this column
            $columnDefinition = $this->columnDefinitions[$column];

            // get the column of data
            $columnData = array_column($data, $column);

            // calculate it based on the widest text for that column
            $columnDefinition->calculateWidth($columnData, $markupDefinition);

        }

    }

Calculate the width of any automatically calculated widths
@param $data


public function draw($data) {

        // if the data is sane, and the widths have been set (if not calculate them)
        if ($this->dataCheck($data)) {

            // calculate the widths
            $this->calculateWidths($data);

            // if at least one of the columns has header text
            if ($this->hasHeader()) {

                // bold and underscore for the title
                $style = new Style();
                $style->setBold()->setUnderscore();

                $headers = $this->getHeaderText();

                // draw the row of cells
                $this->drawRow($headers, $style);

            }

            // go through each row of data
            for ($row = 0; $row<count($data); ++$row) {

                // draw the row of cells
                $this->drawRow($data[$row], null);

            }

        }

    }


public function createSession(SessionManager $sessionManager, $userProfile = null)
    {
        list($sessionId, $fileHandle) = $this->createNewSessionFile();

        $lockFileHandle = null;
        if ($sessionManager->getLockMode() == SessionConfig::LOCK_ON_OPEN) {
            $lockFileHandle = $this->acquireLock(
                $sessionId,
                $sessionManager->getSessionConfig()->getLockMilliSeconds(),
                $sessionManager->getSessionConfig()->getMaxLockWaitTimeMilliseconds()
            );
        }

        $existingProfiles = [];
        if ($userProfile !== null) {
            $existingProfiles[] = $userProfile;
        }

        $fileInfo = new FileInfo($lockFileHandle);
        $this->save($sessionId, [], $existingProfiles,  $fileInfo);
        // fclose($fileHandle); umm.

        return new FileSession(
            $sessionId,
            [],
            $this,
            $sessionManager,
            $existingProfiles,
            $fileInfo,
            false
        );
    }

public
function
createSession
(
SessionManager
$
sessionManager
,
$
userProfile
=
)
{
list
(
$
sessionId
,
$
fileHandle
)
=
$
this
->
createNewSessionFile
(
)
;
$
lockFileHandle
=
;
if
(
$
sessionManager
->
getLockMode
(
)
==
SessionConfig
::
LOCK_ON_OPEN
)
{
$
lockFileHandle
=
$
this
->
acquireLock
(
$
sessionId
,
$
sessionManager
->
getSessionConfig
(
)
->
getLockMilliSeconds
(
)
,
$
sessionManager
->
getSessionConfig
(
)
->
getMaxLockWaitTimeMilliseconds
(
)
)
;
}
$
existingProfiles
=
[
]
;
if
(
$
userProfile
!==
)
{
$
existingProfiles
[
]
=
$
userProfile
;
}
$
fileInfo
=
new
FileInfo
(
$
lockFileHandle
)
;
$
this
->
save
(
$
sessionId
,
[
]
,
$
existingProfiles
,
$
fileInfo
)
;
// fclose($fileHandle); umm.
return
new
FileSession
(
$
sessionId
,
[
]
,
$
this
,
$
sessionManager
,
$
existingProfiles
,
$
fileInfo
,
false
)
;
}

Create a new session.
@param SessionManager $sessionManager
@param null $userProfile
@throws AsmException
@return string The newly created session ID.


private function createNewSessionFile()
    {
        for ($count=0 ; $count<10 ; $count++) {
            $sessionId = $this->idGenerator->generateSessionID();
            $filename = $this->generateFilenameForDataFile($sessionId);
            //TODO remove? - the user should create the directory themselves
            $dirname = dirname($filename);
            @mkdir($dirname);
            //This only succeeds if the file doesn't already exist
            $fileHandle = @fopen($filename, 'x+');
            if ($fileHandle != false) {
                return [$sessionId, $fileHandle];
            }
        };

        throw new AsmException(
            "Failed to open a new session file with random name.",
            AsmException::ID_CLASH
        );
    }

Create a new file safely.

@return array
@throws AsmException


public function save($sessionId, $data, $existingProfiles, FileInfo $fileInfo)
    {
        $rawData = [];
        $rawData['data'] = $data;
        $rawData['profiles'] = $existingProfiles;

        $dataString = $this->serializer->serialize($rawData);
        $filename = $this->generateFilenameForDataFile($sessionId);

        $tempFilename = tempnam(dirname($filename), basename($filename));
        $writeResult = @file_put_contents($tempFilename, $dataString);
        if ($writeResult === false) {
            throw new AsmException(
                "Failed to write session data.",
                AsmException::IO_ERROR
            );
        }
        $tempLockFileHandle = null;

        if ($fileInfo->lockFileHandle) {
            $this->validateLock($sessionId, $fileInfo);
        }
        else {
            $tempLockFileHandle = $this->acquireLock(
                $sessionId,
                5000,
                1000
            );
        }

        //We have the lock - it's safe to replace the datafile
        $renamed = rename($tempFilename, $filename);

        if ($tempLockFileHandle) {
            fclose($tempLockFileHandle);
        }

        if (!$renamed) {
            throw new AsmException(
                "Failed to save session data during rename of file",
                AsmException::IO_ERROR
            );
        }
    }

Saves the data for the sessionID atomically.

@param $sessionId
@param $data
@param $existingProfiles
@param FileInfo $fileInfo
@return resource
@throws AsmException
@throws FailedToAcquireLockException

Saves the data for the sessionID atomically .


public function acquireLock($sessionId, $lockTimeMS, $acquireTimeoutMS)
    {
        // Get the time in MS
        $currentTime = microtime(true);
        $giveUpTime = $currentTime + ($acquireTimeoutMS * 0.001);

        $lockFilename = $this->generateFilenameForLockFile($sessionId);

        do {
            //Re-open the lock file every loop, to prevent issues where another
            //process deletes it.
            $fileHandle = fopen($lockFilename, 'c+');
            //'c+' means "Open the file for writing only. If the file does not exist,
            // it is created. If it exists, it is neither truncated (as opposed to 'w'),
            // nor the call to this function fails (as is the case with 'x').
            $locked = flock($fileHandle, LOCK_EX|LOCK_NB);
            if ($locked) {
                //$touchTime = time() + intval(ceil($lockTimeMS / 1000));
                $expireTime = microtime(true) + ($lockTimeMS * 0.0001);
                file_put_contents(
                    $lockFilename,
                    sprintf("%f", $expireTime)
                );
                //touch($lockFilename, $touchTime);
                return $fileHandle;
            }

            //We did not acquire a lock - check to see if the lock has expired
            $contents = file_get_contents($lockFilename);
            $existingExpireTime = floatval($contents);
            // TODO - we could do a basic sanity test on the lock data
            // however, what we be the correct action to take?
//            if ($existingExpireTime < 1447040641 ||
//                $existingExpireTime > 2551578313) {
//                //lock contents are rubbish
//                //TODO - decide what to do.
//            }

            if (microtime(true) > $existingExpireTime) {
                unlink($lockFilename);
            }
            else {
                // sleep 1ms to avoid churning CPU
                usleep(1000);
            }
        } while($giveUpTime > microtime(true));

        throw new FailedToAcquireLockException(
            "FileDriver failed to acquire lock."
        );
    }

//                $existingExpireTime > 2551578313) {

//                //lock contents are rubbish

//                //TODO - decide what to do.

Acquire a lock for the session
@param $fileHandle
@param $filename
@param $lockTimeMS
@param $acquireTimeoutMS
@return bool
@throws FailedToAcquireLockException


public function sectionForm(
        string $forHandle,
        array $sectionFormOptions = []
    ): FormView {

        $sectionFormOptions = SectionFormOptions::fromArray($sectionFormOptions);

        $form = $this->form->buildFormForSection(
            $forHandle,
            $this->requestStack,
            $sectionFormOptions
        );
        $form->handleRequest();

        if ($form->isSubmitted() &&
            $form->isValid()
        ) {
            $data = $form->getData();
            $this->createSection->save($data);

            try {
                $redirect = $sectionFormOptions->getRedirect();
            } catch (\Exception $exception) {
                $redirect = '/';
            }
            header('Location: ' . $redirect);
            exit;
        }

        return $form->createView();
    }

public
function
sectionForm
(
string
$
forHandle
,
array
$
sectionFormOptions
=
[
]
)
:
FormView
{
$
sectionFormOptions
=
SectionFormOptions
::
fromArray
(
$
sectionFormOptions
)
;
$
form
=
$
this
->
form
->
buildFormForSection
(
$
forHandle
,
$
this
->
requestStack
,
$
sectionFormOptions
)
;
$
form
->
handleRequest
(
)
;
if
(
$
form
->
isSubmitted
(
)
&&
$
form
->
isValid
(
)
)
{
$
data
=
$
form
->
getData
(
)
;
$
this
->
createSection
->
save
(
$
data
)
;
try
{
$
redirect
=
$
sectionFormOptions
->
getRedirect
(
)
;
}
catch
(
\
Exception
$
exception
)
{
$
redirect
=
'/'
;
}
header
(
'Location: '
.
$
redirect
)
;
exit
;
}
return
$
form
->
createView
(
)
;
}

This method returns a form to be rendered with Twig.
It will return a view, validate and save the form data.

@param string $forHandle
@param array $sectionFormOptions
@return FormView

This method returns a form to be rendered with Twig . It will return a view validate and save the form data .


public static function factory($class, $property = null)
    {
        if (is_object($class))
            $class = get_class($class);
        $class = (string)$class;
        if (!isset(self::$properties[$class])) {
            $classReflection = new \ReflectionClass($class);
            $properties = $classReflection->getProperties();
            self::$properties[$class] = array();
            foreach ($properties as $propertyReflection) {
                if ($propertyReflection->class != $class) {
                    self::$properties[$class][$propertyReflection->name] = self::factory($propertyReflection->class, $propertyReflection->name);
                } else {
                    self::$properties[$class][$propertyReflection->name] = new self($propertyReflection->class, $propertyReflection->name);
                    self::$properties[$class][$propertyReflection->name]->setAccessible(true);
                }
            }
        }
        if (isset($property)) {
            if (!isset(self::$properties[$class][$property])) {
                self::$properties[$class][$property] = new self($class, $property);
                self::$properties[$class][$property]->setAccessible(true);
            }
            return self::$properties[$class][$property];
        } else
            return array_values(self::$properties[$class]);
    }

public static function factory ( $ class , $ property = null ) { if ( is_object ( $ class ) ) $ class = get_class ( $ class ) ; $ class = ( string ) $ class ; if ( ! isset ( self :: $ properties [ $ class ] ) ) { $ classReflection = new \ ReflectionClass ( $ class ) ; $ properties = $ classReflection -> getProperties ( ) ; self :: $ properties [ $ class ] = array ( ) ; foreach ( $ properties as $ propertyReflection ) { if ( $ propertyReflection -> class != $ class ) { self :: $ properties [ $ class ] [ $ propertyReflection -> name ] = self :: factory ( $ propertyReflection -> class , $ propertyReflection -> name ) ; } else { self :: $ properties [ $ class ] [ $ propertyReflection -> name ] = new self ( $ propertyReflection -> class , $ propertyReflection -> name ) ; self :: $ properties [ $ class ] [ $ propertyReflection -> name ] -> setAccessible ( true ) ; } } } if ( isset ( $ property ) ) { if ( ! isset ( self :: $ properties [ $ class ] [ $ property ] ) ) { self :: $ properties [ $ class ] [ $ property ] = new self ( $ class , $ property ) ; self :: $ properties [ $ class ] [ $ property ] -> setAccessible ( true ) ; } return self :: $ properties [ $ class ] [ $ property ] ; } else return array_values ( self :: $ properties [ $ class ] ) ; }

Constructs a new ReflectionProperty object from property and class name.
If object already exists in cache it will taken from there instead of creating
new object

@param string|object $class
@param string $property
@return ReflectionProperty

Constructs a new ReflectionProperty object from property and class name . If object already exists in cache it will taken from there instead of creating new object


public function getFacts()
    {
        try {
            $output = $this->runCommand($this->cmd);
            if ($this->as_json) {
                $json = json_decode($output, true);
                if (is_null($json)) {
                    return array();
                }

                return $json;
            } else {
                return $this->parseFacts($output);
            }
        } catch (\Exception $e) {
            return array();
        }
    }

public function getFacts ( ) { try { $ output = $ this -> runCommand ( $ this -> cmd ) ; if ( $ this -> as_json ) { $ json = json_decode ( $ output , true ) ; if ( is_null ( $ json ) ) { return array ( ) ; } return $ json ; } else { return $ this -> parseFacts ( $ output ) ; } } catch ( \ Exception $ e ) { return array ( ) ; } }

Return the facts generated from the command.
If as_json is true, the command must produce valid json.

Return the facts generated from the command . If as_json is true the command must produce valid json .


protected function parseFacts($facts_string)
    {
        $facts = array();
        foreach (explode(PHP_EOL, $facts_string) as $line) {
            if (empty($line)) {
                continue;
            }
            list($key, $value) = explode('=', $line, 2);
            $facts[$key] = $value;
        }

        return $facts;
    }

protected function parseFacts ( $ facts_string ) { $ facts = array ( ) ; foreach ( explode ( PHP_EOL , $ facts_string ) as $ line ) { if ( empty ( $ line ) ) { continue ; } list ( $ key , $ value ) = explode ( '=' , $ line , 2 ) ; $ facts [ $ key ] = $ value ; } return $ facts ; }

Parse flat results in the form
fact1=value1
fact2=value2

Parse flat results in the form fact1 = value1 fact2 = value2


public function findById($id = null)
    {
        $id = $id ?: $this->{$this->tableIdColumn};
        return $this->findWhere("{$this->tableIdColumn} = ?", $id);
    }

public
function
findById
(
$
id
=
)
{
$
id
=
$
id
:
$
this
->
{
$
this
->
tableIdColumn
}
;
return
$
this
->
findWhere
(
"{$this->tableIdColumn} = ?"
,
$
id
)
;
}

Find and return first object by its tableIdColumn and use
its data to populate this instance.

@param integer $id to find or use $this->{$this->tableIdColumn}
as default.

@return this

Find and return first object by its tableIdColumn and use its data to populate this instance .


public function findWhere($where, $value)
    {
        $this->checkDb();
        $params = is_array($value) ? $value : [$value];
        $this->db->connect()
                 ->select()
                 ->from($this ->tableName)
                 ->where($where)
                 ->execute($params)
                 ->fetchInto($this);
    }

public function findWhere ( $ where , $ value ) { $ this -> checkDb ( ) ; $ params = is_array ( $ value ) ? $ value : [ $ value ] ; $ this -> db -> connect ( ) -> select ( ) -> from ( $ this -> tableName ) -> where ( $ where ) -> execute ( $ params ) -> fetchInto ( $ this ) ; }

Find and return first object found by search criteria and use
its data to populate this instance.

The search criteria `$where` of can be set up like this:
`id = ?`
`id1 = ? and id2 = ?`

The `$value` can be a single value or an array of values.

@param string $where to use in where statement.
@param mixed  $value to use in where statement.

@return this

Find and return first object found by search criteria and use its data to populate this instance .


public function findAll()
    {
        $this->checkDb();
        return $this->db->connect()
                        ->select()
                        ->from($this->tableName)
                        ->execute()
                        ->fetchAllClass(get_class($this));
    }

public function findAll ( ) { $ this -> checkDb ( ) ; return $ this -> db -> connect ( ) -> select ( ) -> from ( $ this -> tableName ) -> execute ( ) -> fetchAllClass ( get_class ( $ this ) ) ; }

Find and return all.

@return array of object of this class


public function findAllWhere($where, $value)
    {
        $this->checkDb();
        $params = is_array($value) ? $value : [$value];
        return $this->db->connect()
                        ->select()
                        ->from($this->tableName)
                        ->where($where)
                        ->execute($params)
                        ->fetchAllClass(get_class($this));
    }

public function findAllWhere ( $ where , $ value ) { $ this -> checkDb ( ) ; $ params = is_array ( $ value ) ? $ value : [ $ value ] ; return $ this -> db -> connect ( ) -> select ( ) -> from ( $ this -> tableName ) -> where ( $ where ) -> execute ( $ params ) -> fetchAllClass ( get_class ( $ this ) ) ; }

Find and return all matching the search criteria.

The search criteria `$where` of can be set up like this:
`id = ?`
`id IN [?, ?]`

The `$value` can be a single value or an array of values.

@param string $where to use in where statement.
@param mixed  $value to use in where statement.

@return array of object of this class

Find and return all matching the search criteria .


protected function create()
    {
        $this->checkDb();
        $properties = $this->getProperties();
        unset($properties[$this->tableIdColumn]);
        $columns = array_keys($properties);
        $values  = array_values($properties);

        $this->db->connect()
                 ->insert($this->tableName, $columns)
                 ->execute($values);

        $this->{$this->tableIdColumn} = $this->db->lastInsertId();
    }

protected function create ( ) { $ this -> checkDb ( ) ; $ properties = $ this -> getProperties ( ) ; unset ( $ properties [ $ this -> tableIdColumn ] ) ; $ columns = array_keys ( $ properties ) ; $ values = array_values ( $ properties ) ; $ this -> db -> connect ( ) -> insert ( $ this -> tableName , $ columns ) -> execute ( $ values ) ; $ this -> { $ this -> tableIdColumn } = $ this -> db -> lastInsertId ( ) ; }


protected function updateWhere($where, $value)
    {
        $this->checkDb();
        $properties = $this->getProperties();
        $columns = array_keys($properties);
        $values  = array_values($properties);
        $values1 = is_array($value)
            ? $value
            : [$value];
        $values = array_merge($values, $values1);

        $this->db->connect()
                 ->update($this->tableName, $columns)
                 ->where($where)
                 ->execute($values);
    }

protected function updateWhere ( $ where , $ value ) { $ this -> checkDb ( ) ; $ properties = $ this -> getProperties ( ) ; $ columns = array_keys ( $ properties ) ; $ values = array_values ( $ properties ) ; $ values1 = is_array ( $ value ) ? $ value : [ $ value ] ; $ values = array_merge ( $ values , $ values1 ) ; $ this -> db -> connect ( ) -> update ( $ this -> tableName , $ columns ) -> where ( $ where ) -> execute ( $ values ) ; }

Update row using a custom where-statement.

The criteria `$where` of can be set up like this:
`id = ?`
`id1 = ? AND id2 = ?`
`id IN (?, ?)`

The `$value` can be a single value or an array of values.

@param string $where to use in where statement.
@param mixed  $value to use in where statement.

@return void

Update row using a custom where - statement .


protected function parseNotation($notation)
    {
        $out = str_replace(['[', ']'], ['(?:', ')?'], $notation);

        $enhancement = '(?P<\2>' . self::REGVAL . ')';
        $out = preg_replace(self::REGKEY, $enhancement, $out);

        return $out;
    }

protected function parseNotation ( $ notation ) { $ out = str_replace ( [ '[' , ']' ] , [ '(?:' , ')?' ] , $ notation ) ; $ enhancement = '(?P<\2>' . self :: REGVAL . ')' ; $ out = preg_replace ( self :: REGKEY , $ enhancement , $ out ) ; return $ out ; }

Turns route notation in a regular expression


protected function applyConditions($expression, $conditions)
    {
        $search = $replace = [];

        foreach ($conditions as $key => $value) {
            $search[]  = "<$key>" . self::STRVAL;
            $replace[] = "<$key>$value";
        }

        return str_replace($search, $replace, $expression);
    }

protected function applyConditions ( $ expression , $ conditions ) { $ search = $ replace = [ ] ; foreach ( $ conditions as $ key => $ value ) { $ search [ ] = "<$key>" . self :: STRVAL ; $ replace [ ] = "<$key>$value" ; } return str_replace ( $ search , $ replace , $ expression ) ; }

Inserts custom patterns in the existing regular expression


public function calculate(): FormulasInterface
    {
        if (! $this->dataSet instanceof DataSet) {
            throw new WrongUsageException('DataSet was not provided for mean calculus');
        }

        $dataSetSize = $this->dataSet->getSize();
        $this->result = [];

        foreach ($this->dataSet as $instance) {
            foreach ($instance->getDimensions() as $index => $dimension) {
                $this->result[0][$index] = $this->result[0][$index] ?? 0;
                $this->result[0][$index] += $dimension / $dataSetSize;
            }
            foreach ($instance->getOutputs() as $index => $output) {
                $this->result[1][$index] = $this->result[1][$index] ?? 0;
                $this->result[1][$index] += $output / $dataSetSize;
            }
        }

        return $this;
    }

calculate the mean of the dataSet
@return FormulasInterface
@throws WrongUsageException


public function create(HttpClient $client = null): PluginClient
    {
        return new PluginClient($client ?? HttpClientDiscovery::find(), $this->plugins);
    }

public function create ( HttpClient $ client = null ) : PluginClient { return new PluginClient ( $ client ?? HttpClientDiscovery :: find ( ) , $ this -> plugins ) ; }

Build the HTTP client to talk to the API.

Build the HTTP client to talk to the API .


public function setFile($file, $contentDisposition = null, $etag = false, $lastModified = true)
	{
		if (!$file instanceof File) {
			if ($file instanceof \SplFileInfo) {
				$file = new File($file->getPathname());
			} else {
				$file = new File((string) $file);
			}
		}

		if (!$file->isReadable()) {
			throw new FileException('File must be readable.');
		}

		$this->file = $file;

		if ($etag === true)
			$this->setAutoEtag();
		elseif (!empty($etag))
			$this->setEtag($etag);

		if ($lastModified === true)
			$this->setAutoLastModified();
		elseif (!empty($lastModified))
		{
			is_numeric($lastModified) && $lastModified = '@'.$lastModified;
			$this->setLastModified(new \DateTime($lastModified));
		}

		if ($contentDisposition)
			$this->setContentDisposition($contentDisposition);

		return $this;
	}

public
function
setFile
(
$
file
,
$
contentDisposition
=
,
$
etag
=
false
,
$
lastModified
=
true
)
{
if
(
!
$
file
instanceof
File
)
{
if
(
$
file
instanceof
\
SplFileInfo
)
{
$
file
=
new
File
(
$
file
->
getPathname
(
)
)
;
}
else
{
$
file
=
new
File
(
(
string
)
$
file
)
;
}
}
if
(
!
$
file
->
isReadable
(
)
)
{
throw
new
FileException
(
'File must be readable.'
)
;
}
$
this
->
file
=
$
file
;
if
(
$
etag
===
true
)
$
this
->
setAutoEtag
(
)
;
elseif
(
!
empty
(
$
etag
)
)
$
this
->
setEtag
(
$
etag
)
;
if
(
$
lastModified
===
true
)
$
this
->
setAutoLastModified
(
)
;
elseif
(
!
empty
(
$
lastModified
)
)
{
is_numeric
(
$
lastModified
)
&&
$
lastModified
=
'@'
.
$
lastModified
;
$
this
->
setLastModified
(
new
\
DateTime
(
$
lastModified
)
)
;
}
if
(
$
contentDisposition
)
$
this
->
setContentDisposition
(
$
contentDisposition
)
;
return
$
this
;
}

Sets the file to stream.

@param \SplFileInfo|string $file               The file to stream
@param string              $contentDisposition
@param bool                $autoEtag
@param bool                $autoLastModified

@return BinaryFileResponse

@throws FileException


public function addTemplate($name, $url, $ttl, array $blocks, array $metadata)
    {
        $this->templates[$name] = [
            'url' => $url,
            'ttl' => $ttl,
            'blocks' => $blocks,
            'metadata' => $metadata,
            'checked_ttl' => false,
            'checking_ttl' => false,
        ];
    }

public function addTemplate ( $ name , $ url , $ ttl , array $ blocks , array $ metadata ) { $ this -> templates [ $ name ] = [ 'url' => $ url , 'ttl' => $ ttl , 'blocks' => $ blocks , 'metadata' => $ metadata , 'checked_ttl' => false , 'checking_ttl' => false , ] ; }

Add a remote template.

@param string $name
@param string $url
@param int    $ttl
@param array  $blocks
@param array  $metadata


private function checkCacheFileTtl($name)
    {
        // this method is called only if env->isAutoReload() == FALSE
        if (
            false !== ($cacheFile = $this->container->get('twig')->getCacheFilename($name))
            && \is_file($cacheFile)
            && \time() - \filemtime($cacheFile) >= $this->templates[$name]['ttl']
        ) {
            // remove expired cache file
            \unlink($cacheFile);
        }
    }

Check cache file TTL.

@param string $name


private function placeholdersToBlocks(array $blocks, $source)
    {
        $usedBlockMap = [];
        $placeholderToBlockMap = [];

        $pattern = '';
        $first = true;
        foreach ($blocks as $blockName => $block) {
            $first ? $first = false : $pattern .= '|';
            $pattern .= \preg_quote($block['placeholder'], '/');

            $placeholderToBlockMap[$block['placeholder']] = $blockName;
        }

        return \preg_replace_callback(
            \sprintf('/(%s)/', $pattern),
            function (array $match) use ($placeholderToBlockMap, &$usedBlockMap) {
                $blockName = $placeholderToBlockMap[$match[0]];

                if (isset($usedBlockMap[$blockName])) {
                    return $this->createRepeatedPlaceholderBlockSyntax($blockName);
                }
                $usedBlockMap[$blockName] = true;

                return $this->createPlaceholderBlockSyntax($blockName);
            },
            $source
        );
    }

private function placeholdersToBlocks ( array $ blocks , $ source ) { $ usedBlockMap = [ ] ; $ placeholderToBlockMap = [ ] ; $ pattern = '' ; $ first = true ; foreach ( $ blocks as $ blockName => $ block ) { $ first ? $ first = false : $ pattern .= '|' ; $ pattern .= \ preg_quote ( $ block [ 'placeholder' ] , '/' ) ; $ placeholderToBlockMap [ $ block [ 'placeholder' ] ] = $ blockName ; } return \ preg_replace_callback ( \ sprintf ( '/(%s)/' , $ pattern ) , function ( array $ match ) use ( $ placeholderToBlockMap , & $ usedBlockMap ) { $ blockName = $ placeholderToBlockMap [ $ match [ 0 ] ] ; if ( isset ( $ usedBlockMap [ $ blockName ] ) ) { return $ this -> createRepeatedPlaceholderBlockSyntax ( $ blockName ) ; } $ usedBlockMap [ $ blockName ] = true ; return $ this -> createPlaceholderBlockSyntax ( $ blockName ) ; } , $ source ) ; }

Convert placeholders to blocks in the source.

@param array  $blocks
@param string $source

@return string

Convert placeholders to blocks in the source .


private function getMetadata($name)
    {
        $this->ensureExists($name);

        return
            ['url' => $this->templates[$name]['url']]
            + $this->templates[$name]['metadata'];
    }

private function getMetadata ( $ name ) { $ this -> ensureExists ( $ name ) ; return [ 'url' => $ this -> templates [ $ name ] [ 'url' ] ] + $ this -> templates [ $ name ] [ 'metadata' ] ; }

Get template metadata array.

@param string $name template name

@return string


public static function buildDefinitionProvider(Discovery $discovery)
    {
        $bindings = $discovery->findBindings('definition-interop/yaml-definition-files');

        $definitionProviders = [];

        foreach ($bindings as $binding) {
            foreach ($binding->getResources() as $resource) {
                /* @var $resource FileResource */
                $definitionProviders[] = new YamlDefinitionLoader($resource->getFilesystemPath());
            }
        }

        return self::mergeDefinitionProviders($definitionProviders);
    }

Creates a definition provider.

@param Discovery $discovery

@return DefinitionProviderInterface


public function of(string $formulaName)
    {
        if (! isset($this->results[$formulaName])) {
            throw new CalculusResultNotFound('No result found for the given formula : ' . $formulaName );
        }

        return $this->results[$formulaName];
    }

Returns a specific result by key
@param string $formulaName
@return mixed
@throws CalculusResultNotFound


public function save(FormulasInterface $formula): FormulasResults
    {
        if ($this->isValid($formula)) {
            $this->results[get_class($formula)] = $formula->getResult();
        }

        //the stack contains all the formulas called (a callstack)
        $this->stack[] = $formula;

        return $this;
    }

Save the results of a given formula to keep in the history
@param FormulasInterface $formula
@return FormulasResults


public function addHeader(ItemInterface $item, $text)
    {
        return $item->addChild('header_' . \rand())
            ->setLabel($text)
            ->setAttribute('class', 'nav-header');
    }

public function addHeader ( ItemInterface $ item , $ text ) { return $ item -> addChild ( 'header_' . \ rand ( ) ) -> setLabel ( $ text ) -> setAttribute ( 'class' , 'nav-header' ) ; }

Adds a menu header.

@param ItemInterface $item
@param $text

@return ItemInterface


public function setDropdown(ItemInterface $dropDownItem)
    {
        $dropDownItem
            ->setUri('#')
            ->setLinkattribute('class', 'dropdown-toggle')
            ->setLinkattribute('data-toggle', 'dropdown')
            ->setAttribute('class', 'dropdown')
            ->setChildrenAttribute('class', 'dropdown-menu');

        $dropDownItem->setLabel($dropDownItem->getLabel() . '<b class="caret"></b>');
        $dropDownItem->setExtra('safe_label', true);
    }

public
function
setDropdown
(
ItemInterface
$
dropDownItem
)
{
$
dropDownItem
->
setUri
(
'#'
)
->
setLinkattribute
(
'class'
,
'dropdown-toggle'
)
->
setLinkattribute
(
'data-toggle'
,
'dropdown'
)
->
setAttribute
(
'class'
,
'dropdown'
)
->
setChildrenAttribute
(
'class'
,
'dropdown-menu'
)
;
$
dropDownItem
->
setLabel
(
$
dropDownItem
->
getLabel
(
)
.
'<b class="caret"></b>'
)
;
$
dropDownItem
->
setExtra
(
'safe_label'
,
true
)
;
}

Creates a drop down menu item from item.

@param ItemInterface $dropDownItem

Creates a drop down menu item from item .


public function isUserGranted($attributes, $subject = null): bool
    {
        return $this->security->isGranted($attributes, $subject);
    }

public function isUserGranted ( $ attributes , $ subject = null ) : bool { return $ this -> security -> isGranted ( $ attributes , $ subject ) ; }

Checks if the attributes are granted against the current authentication token and optionally supplied object.

@param mixed $attributes
@param mixed $subject

@return bool

Checks if the attributes are granted against the current authentication token and optionally supplied object .


public function download($file, $name = null, array $headers = [], $options = [], $disposition = 'attachment')
	{
		!empty($options['cached']) && $headers = array_merge($headers, ['Cache-Control' => 'private, max-age=3600, must-revalidate', 'Pragma' => 'cache']);
		!empty($options['mime_type']) && $headers = array_merge($headers, ['Content-Type' => $options['mime_type']]);

		$response = new BinaryFileResponse($file, 200, $headers, true, $disposition);

		if (isset($options['last_modified']))
			$response->setLastModified($options['last_modified']);

		if (isset($options['etag']))
			$response->setEtag($options['etag']);

		if (!is_null($name))
			$response->setContentDisposition($disposition, $name, str_replace('%', '', Str::ascii($name)));

		return $response;
	}

Create a new file download response.

@param  \SplFileInfo|string  $file
@param  string  $name
@param  array  $headers
@param  string|null  $disposition
@return \Symfony\Component\HttpFoundation\BinaryFileResponse


private function getUrl($type, $key)
    {
        switch ($type) {
            case 'album':
                $url = 'album/%s/';
                break;
            case 'photo':
                $url = 'photo/%s/';
                break;
            case 'albumPhotos':
                $url = 'album/%s/photos/';
                break;
            case 'albums':
                $url = 'albums/';
                break;
            case 'tags':
                $url = 'tags/';
                break;
            case 'tag':
                $url = 'tag/%s/photos/';
                break;
            default:
                $url = '/';
        }

        return sprintf($url, $key);
    }

private function getUrl ( $ type , $ key ) { switch ( $ type ) { case 'album' : $ url = 'album/%s/' ; break ; case 'photo' : $ url = 'photo/%s/' ; break ; case 'albumPhotos' : $ url = 'album/%s/photos/' ; break ; case 'albums' : $ url = 'albums/' ; break ; case 'tags' : $ url = 'tags/' ; break ; case 'tag' : $ url = 'tag/%s/photos/' ; break ; default : $ url = '/' ; } return sprintf ( $ url , $ key ) ; }

get Api Url

@param  string $type album|photo|albumPhotos|albums or base path
@param  string $key

@return string


private function setListCover(array $listCover, Gallery $album)
    {
        foreach ($listCover as $image) {
            $album->addCover(new Meta($image['href'], $image['width'], $image['height']));
        }
    }

private function setListCover ( array $ listCover , Gallery $ album ) { foreach ( $ listCover as $ image ) { $ album -> addCover ( new Meta ( $ image [ 'href' ] , $ image [ 'width' ] , $ image [ 'height' ] ) ) ; } }

set Cover List

@param array   $listCover
@param Gallery $album


private function getDataByType($key, $type = 'photo')
    {
        $url = $this->getUrl($type, $key);

        return $this->getData($url);
    }

private function getDataByType ( $ key , $ type = 'photo' ) { $ url = $ this -> getUrl ( $ type , $ key ) ; return $ this -> getData ( $ url ) ; }

get Data By Type

@param  string $key
@param  string $type

@return array


private function getData($url)
    {
        try {
            $request = $this->client->get($url);
            $response = $request->send();
            $decoder = new JsonDecode(true);
            $data = $decoder->decode($response->getBody(true), 'json');
            if (isset($data['links']['next'])) {
                $next = $this->getData($data['links']['next']);
                $data['entries'] = array_merge($data['entries'], $next['entries']);
            }
        } catch (\Exception $e) {
            $data = array();
        }

        return $data;
    }

private function getData ( $ url ) { try { $ request = $ this -> client -> get ( $ url ) ; $ response = $ request -> send ( ) ; $ decoder = new JsonDecode ( true ) ; $ data = $ decoder -> decode ( $ response -> getBody ( true ) , 'json' ) ; if ( isset ( $ data [ 'links' ] [ 'next' ] ) ) { $ next = $ this -> getData ( $ data [ 'links' ] [ 'next' ] ) ; $ data [ 'entries' ] = array_merge ( $ data [ 'entries' ] , $ next [ 'entries' ] ) ; } } catch ( \ Exception $ e ) { $ data = array ( ) ; } return $ data ; }

get Data By Url

@param string $url

@return array


public static function install($baseUri = null) {
		$baseUri = $baseUri ? "$baseUri/" : "";
        \Route::post($baseUri . "resources/bulk/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@postBulk");
        \Route::put($baseUri . "resources/bulk/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@putBulk");
        \Route::put($baseUri . "resources/{resource}/{id}/link/{relation}/{related}/{relatedId}", "Foothing\RepositoryController\Controllers\ResourceController@putLink");
        \Route::delete($baseUri . "resources/{resource}/{id}/link/{relation}/{related}/{relatedId}", "Foothing\RepositoryController\Controllers\ResourceController@deleteLink");
        \Route::get($baseUri . "resources/{resource}/{id?}/{args?}", "Foothing\RepositoryController\Controllers\ResourceController@getIndex")->where('args', '[a-zA-Z0-9/_]*');
		\Route::put($baseUri . "resources/{resource}/{id}", "Foothing\RepositoryController\Controllers\ResourceController@putIndex");
		\Route::delete($baseUri . "resources/{resource}/{id}", "Foothing\RepositoryController\Controllers\ResourceController@deleteIndex");
		\Route::post($baseUri . "resources/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@postIndex");
	}

Install route patterns.

@param null $baseUri


private function isValidDate($date){
        return preg_match('#[0-3][0-9]\/[0-1][0-9]\/[2][0][0-9][0-9]#', $date)
               &&
               checkdate((int)substr($date, 3, 2),
                         (int)substr($date, 0, 2),
                         (int)substr($date, 6, 4));
    }

Checks if a date string is valid
@param $date
@return bool


public function wrap_gui_frame( $content ){
		$this->bowl()->send($content);
		unset($content);

		@header( 'Content-type: text/html; charset="UTF-8"' );

		// リソースをキャッシュ領域にコピー
		$path_pxcache = $this->px->fs()->get_realpath( $this->px->get_path_controot().$this->px->conf()->public_cache_dir.'/px/' );
		$realpath_pxcache = $this->px->fs()->get_realpath( $this->px->get_realpath_docroot().$path_pxcache );
		$this->px->fs()->mkdir( $realpath_pxcache );
		$this->px->fs()->copy_r( __DIR__.'/files/', $realpath_pxcache );

		$pxcmd = $this->px->get_px_command();
		ob_start();?>
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<title><?= htmlspecialchars( $this->px->conf()->name ) ?></title>

		<link rel="stylesheet" href="<?= htmlspecialchars( $path_pxcache.'styles/bootstrap/css/bootstrap.min.css' ); ?>">

		<link rel="stylesheet" href="<?= htmlspecialchars( $path_pxcache.'styles/contents.css' ); ?>" type="text/css" />

		<link rel="stylesheet" href="<?= htmlspecialchars( $path_pxcache.'styles/layout.css' ); ?>" type="text/css" />

<?= $this->bowl()->pull('head') ?>

<?= $this->px->get_pickles_logo_svg() ?> Pickles 2 (version: <?= htmlspecialchars( $this->px->get_version() ) ?>)

<?php
	// $pxcommands = $this->pxcommands;
	// if( count($pxcommands) ){
	// 	print '<select onchange="window.location.href=\'?PX=\'+this.options[this.selectedIndex].value;">';
	// 	foreach( $pxcommands as $row ){
	// 		print '<option value="'.htmlspecialchars($row['cmd']).'"'.($row['cmd']==$pxcmd[0]?' selected="selected"':'').'>'.htmlspecialchars($row['name']).'</option>';
	// 	}
	// 	print '</select>';
	// }
?>

<?= htmlspecialchars( @$this->px->conf()->name ) ?>

<?php
		$command_title = $pxcmd[0].(@strlen($pxcmd[1])?'.'.$pxcmd[1]:'');
		$page_title = null;
?>

		<?php if(strlen($page_title)){ ?>

<a href="?PX=<?= htmlspecialchars( $command_title ) ?>" style="color:inherit; text-decoration:none;"><?= htmlspecialchars($command_title) ?>

<?= htmlspecialchars( $page_title ) ?>

		<?php }else{ ?>

<a href="?PX=<?= htmlspecialchars( $command_title ) ?>" style="color:inherit; text-decoration:none;"><?= htmlspecialchars( $command_title ) ?>

		<?php } ?>

<?= $this->bowl()->pull() ?>

PX Commands を終了する

PHP <?= htmlspecialchars(phpversion()) ?>

<?= htmlspecialchars(@date('Y-m-d H:i:s')) ?>

Pickles Framework (C)Tomoya Koyanagi.

<?php
		return ob_get_clean();
	}

// リソースをキャッシュ領域にコピー

?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title><?=

?></title>

		<!-- jQuery -->
		<script src="<?=

?>" type="text/javascript"></script>

		<!-- Bootstrap -->
		<link rel="stylesheet" href="<?=

?>"></script>

		<!-- FESS -->
		<link rel="stylesheet" href="<?=

?>" type="text/css" />

		<!-- layout -->
		<link rel="stylesheet" href="<?=

?>
			</div><!-- /.pxcmd-title -->
			<div id="content" class="contents">
<?=

wrap GUI frame

@param string $content コンテンツ領域のHTMLソースコード
@return string HTML全体のHTMLソースコード


public function run($commandline)
    {
        $this->bootstrap();

        $artisan = $this->getArtisan();
		$artisan->setCatchExceptions(false);
		$artisan->run($input = new \Symfony\Component\Console\Input\StringInput(trim(str_replace('php artisan', '', $commandline))), $out = new \Symfony\Component\Console\Output\BufferedOutput);
		$artisan->setCatchExceptions(true);
        return $out;
    }

public
function
run
(
$
commandline
)
{
$
this
->
bootstrap
(
)
;
$
artisan
=
$
this
->
getArtisan
(
)
;
$
artisan
->
setCatchExceptions
(
false
)
;
$
artisan
->
run
(
$
input
=
new
\
Symfony
\
Component
\
Console
\
Input
\
StringInput
(
trim
(
str_replace
(
'php artisan'
,
''
,
$
commandline
)
)
)
,
$
out
=
new
\
Symfony
\
Component
\
Console
\
Output
\
BufferedOutput
)
;
$
artisan
->
setCatchExceptions
(
true
)
;
return
$
out
;
}

Run an Artisan console command by name.

@param  string  $command
@param  array  $parameters
@return int

Run an Artisan console command by name .


public static function factory($class, $method = null)
    {
        if (is_object($class))
            $class = get_class($class);
        $class = (string)$class;
        if (!isset(self::$methods[$class])) {
            $classReflection = new \ReflectionClass($class);
            $methods = $classReflection->getMethods();
            self::$methods[$class] = array();
            foreach ($methods as $methodReflection) {
                if ($methodReflection->class != $class) {
                    self::$methods[$class][$methodReflection->name] = self::factory($methodReflection->class, $methodReflection->name);
                } else {
                    self::$methods[$class][$methodReflection->name] = new self($class, $methodReflection->name);
                    self::$methods[$class][$methodReflection->name]->setAccessible(true);
                }
            }
        }
        if (isset($method)) {
            if (!isset(self::$methods[$class][$method])) {
                self::$methods[$class][$method] = new self($class, $method);
                self::$methods[$class][$method]->setAccessible(true);
            }
            return self::$methods[$class][$method];
        } else
            return array_values(self::$methods[$class]);
    }

public static function factory ( $ class , $ method = null ) { if ( is_object ( $ class ) ) $ class = get_class ( $ class ) ; $ class = ( string ) $ class ; if ( ! isset ( self :: $ methods [ $ class ] ) ) { $ classReflection = new \ ReflectionClass ( $ class ) ; $ methods = $ classReflection -> getMethods ( ) ; self :: $ methods [ $ class ] = array ( ) ; foreach ( $ methods as $ methodReflection ) { if ( $ methodReflection -> class != $ class ) { self :: $ methods [ $ class ] [ $ methodReflection -> name ] = self :: factory ( $ methodReflection -> class , $ methodReflection -> name ) ; } else { self :: $ methods [ $ class ] [ $ methodReflection -> name ] = new self ( $ class , $ methodReflection -> name ) ; self :: $ methods [ $ class ] [ $ methodReflection -> name ] -> setAccessible ( true ) ; } } } if ( isset ( $ method ) ) { if ( ! isset ( self :: $ methods [ $ class ] [ $ method ] ) ) { self :: $ methods [ $ class ] [ $ method ] = new self ( $ class , $ method ) ; self :: $ methods [ $ class ] [ $ method ] -> setAccessible ( true ) ; } return self :: $ methods [ $ class ] [ $ method ] ; } else return array_values ( self :: $ methods [ $ class ] ) ; }

Constructs a new ReflectionMethod object from method and class name.
If object already exists in cache it will taken from there instead of creating
new object

@param string|object $class
@param string $property
@return ReflectionMethod

Constructs a new ReflectionMethod object from method and class name . If object already exists in cache it will taken from there instead of creating new object


function createSession(SessionManager $sessionManager, $userProfile = null)
    {
        $sessionLifeTime = $sessionManager->getSessionConfig()->getLifetime();
        $initialData = [];
        $profiles = [];
        if ($userProfile) {
            $profiles = [$userProfile];
        }
        $initialData['profiles'] = $profiles;
        $initialData['data'] = [];
        $dataString = $this->serializer->serialize($initialData);

        $lockToken = null;

        for ($count = 0; $count < 10; $count++) {
            $sessionId = $this->idGenerator->generateSessionID();
            $lockToken = $this->acquireLockIfRequired($sessionId, $sessionManager);
            $dataKey = generateSessionDataKey($sessionId);
            $set = $this->redisClient->set(
                $dataKey,
                $dataString,
                'EX',
                $sessionLifeTime,
                'NX'
            );

            if ($set) {
                return new RedisSession(
                    $sessionId,
                    $this,
                    $sessionManager,
                    [],
                    $profiles,
                    false,
                    $lockToken
                );
            }

            if ($lockToken !== null) {
                $this->releaseLock($sessionId, $lockToken);
            }
        }

        throw new AsmException(
            "Failed to createSession.",
            AsmException::ID_CLASH
        );
    }

function
createSession
(
SessionManager
$
sessionManager
,
$
userProfile
=
)
{
$
sessionLifeTime
=
$
sessionManager
->
getSessionConfig
(
)
->
getLifetime
(
)
;
$
initialData
=
[
]
;
$
profiles
=
[
]
;
if
(
$
userProfile
)
{
$
profiles
=
[
$
userProfile
]
;
}
$
initialData
[
'profiles'
]
=
$
profiles
;
$
initialData
[
'data'
]
=
[
]
;
$
dataString
=
$
this
->
serializer
->
serialize
(
$
initialData
)
;
$
lockToken
=
;
for
(
$
count
=
0
;
$
count
<
10
;
$
count
++
)
{
$
sessionId
=
$
this
->
idGenerator
->
generateSessionID
(
)
;
$
lockToken
=
$
this
->
acquireLockIfRequired
(
$
sessionId
,
$
sessionManager
)
;
$
dataKey
=
generateSessionDataKey
(
$
sessionId
)
;
$
set
=
$
this
->
redisClient
->
set
(
$
dataKey
,
$
dataString
,
'EX'
,
$
sessionLifeTime
,
'NX'
)
;
if
(
$
set
)
{
return
new
RedisSession
(
$
sessionId
,
$
this
,
$
sessionManager
,
[
]
,
$
profiles
,
false
,
$
lockToken
)
;
}
if
(
$
lockToken
!==
)
{
$
this
->
releaseLock
(
$
sessionId
,
$
lockToken
)
;
}
}
throw
new
AsmException
(
"Failed to createSession."
,
AsmException
::
ID_CLASH
)
;
}

Create a new session
@return RedisSession
@param SessionManager $sessionManager
@param null $userProfile
@throws AsmException


private function sendEntity($entity_name, array $data, $key_id)
    {
        $client = $this->getClient();
        $this->getLogger()->info('Sending new ' . $entity_name . '.');
        try {
            $this->getLogger()->info('Try to PUT data to existing ' . $entity_name . ' record.');
            $data[$key_id . '_uri'] = $data[$key_id];
            $client->getCommand('put' . $entity_name, $data)
                ->execute();
        } catch (ClientErrorResponseException $e) {
            if ($e->getResponse()->getStatusCode() === 404) {
                // The server doesn't exist yet. We need to POST it.
                $this->getLogger()->info($entity_name . ' was not found on PUT request. Doing POST to create it.');
                $client->getCommand('post' . $entity_name, $data)
                    ->execute();
            } else {
                // This is not a 404 error, throw the exception.
                throw $e;
            }
        }
        $this->getLogger()->info('The ' . $entity_name . ' information has been successfully sent.');
    }

Send an entity.
Try put first if 404 create it with POST.

@param string $entity_name Entity name in CamelCase
@param array  $data        Entity data to send.
@param string $key_id      Key of data to use as an id for the request.

Send an entity . Try put first if 404 create it with POST .


public function registerProviders()
    {
        $finder = new Finder();
        $finder->files()
            ->ignoreUnreadableDirs()
            ->in($this->providers_dir)
            ->sortByName()
            ->name('*.php');
        foreach ($finder as $provider) {
            $this->registerProviderFromFile($provider);
        }
    }

public function registerProviders ( ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> ignoreUnreadableDirs ( ) -> in ( $ this -> providers_dir ) -> sortByName ( ) -> name ( '*.php' ) ; foreach ( $ finder as $ provider ) { $ this -> registerProviderFromFile ( $ provider ) ; } }

List the files in the providers dir to create new objects.

List the files in the providers dir to create new objects .


public function registerProviderFromFile(\SplFileInfo $provider_file)
    {
        $class_name = $this->providers_namespace . '\\' . $provider_file->getBasename('.php');
        $this->addProvider($this->factory($class_name));
    }

public function registerProviderFromFile ( \ SplFileInfo $ provider_file ) { $ class_name = $ this -> providers_namespace . '\\' . $ provider_file -> getBasename ( '.php' ) ; $ this -> addProvider ( $ this -> factory ( $ class_name ) ) ; }


public function getFacts($cached = true)
    {
        if (is_null($this->facts)) {
            $this->populateFacts();
        }

        return $this->facts;
    }

public function getFacts ( $ cached = true ) { if ( is_null ( $ this -> facts ) ) { $ this -> populateFacts ( ) ; } return $ this -> facts ; }


public function populateFacts()
    {
        $this->facts = array();
        foreach ($this->providers as $provider) {
            $this->facts = array_replace_recursive($this->facts, $provider->getFacts());
        }
    }

public function populateFacts ( ) { $ this -> facts = array ( ) ; foreach ( $ this -> providers as $ provider ) { $ this -> facts = array_replace_recursive ( $ this -> facts , $ provider -> getFacts ( ) ) ; } }

Fill from facts from providers for caching.

Fill from facts from providers for caching .


private function record($domainEvent)
    {
        $this->ensureChangesEventStream();
        $this->changes = $this->changes->append($domainEvent);
    }

private function record ( $ domainEvent ) { $ this -> ensureChangesEventStream ( ) ; $ this -> changes = $ this -> changes -> append ( $ domainEvent ) ; }

Record a Domain Event

@param mixed $domainEvent


public function apply($domainEvent)
    {
        $domainEvent = $this->ensureDomainEvent($domainEvent);
        $eventHandlerName = $this->getEventHandlerName($domainEvent);
        if (method_exists($this, $eventHandlerName)) {
            $this->executeEventHandler($this, $eventHandlerName, $domainEvent);
        } else {
            $this->applyRecursively($eventHandlerName, $domainEvent);
        }
    }

public function apply ( $ domainEvent ) { $ domainEvent = $ this -> ensureDomainEvent ( $ domainEvent ) ; $ eventHandlerName = $ this -> getEventHandlerName ( $ domainEvent ) ; if ( method_exists ( $ this , $ eventHandlerName ) ) { $ this -> executeEventHandler ( $ this , $ eventHandlerName , $ domainEvent ) ; } else { $ this -> applyRecursively ( $ eventHandlerName , $ domainEvent ) ; } }

Apply a Domain Event to the aggregate

@param mixed $domainEvent


private function fnc_call_plugin_funcs( $func_list ){
		if( is_null($func_list) ){ return false; }
		$param_arr = func_get_args();
		array_shift($param_arr);

		if( @!empty( $func_list ) ){
			// functions
			if( is_object($func_list) ){
				$func_list = get_object_vars( $func_list );
			}
			if( is_string($func_list) ){
				$fnc_name = $func_list;
				$fnc_name = preg_replace( '/^\\\\*/', '\\', $fnc_name );
				$option_value = null;
				preg_match( '/^(.*?)(?:\\((.*)\\))?$/s', $fnc_name, $matched );
				if(array_key_exists( 1, $matched )){
					$fnc_name = @$matched[1];
				}
				if(array_key_exists( 2, $matched )){
					$option_value = @$matched[2];
				}
				unset($matched);
				if( strlen( trim($option_value) ) ){
					$option_value = json_decode( $option_value );
				}else{
					$option_value = null;
				}
				// var_dump($fnc_name);
				// var_dump($option_value);
				$this->proc_num ++;
				if( @!strlen($this->proc_id) ){
					$this->proc_id = $this->proc_type.'_'.$this->proc_num;
				}
				array_push( $param_arr, $option_value );
				call_user_func_array( $fnc_name, $param_arr);
				$this->proc_id = null;

			}elseif( is_array($func_list) ){
				foreach( $func_list as $fnc_id=>$fnc_name ){
					if( is_string($fnc_name) ){
						$fnc_name = preg_replace( '/^\\\\*/', '\\', $fnc_name );
					}
					if( is_string($fnc_id) && !preg_match('/^[0-9]+$/', $fnc_id) ){
						$this->proc_id = $fnc_id;
					}
					$param_arr_dd = $param_arr;
					array_unshift( $param_arr_dd, $fnc_name );
					call_user_func_array( array( $this, 'fnc_call_plugin_funcs' ), $param_arr_dd);
				}
			}
			unset($fnc_name);
		}
		return true;
	}

private
function
fnc_call_plugin_funcs
(
$
func_list
)
{
if
(
is_null
(
$
func_list
)
)
{
return
false
;
}
$
param_arr
=
func_get_args
(
)
;
array_shift
(
$
param_arr
)
;
if
(
@
!
empty
(
$
func_list
)
)
{
// functions
if
(
is_object
(
$
func_list
)
)
{
$
func_list
=
get_object_vars
(
$
func_list
)
;
}
if
(
is_string
(
$
func_list
)
)
{
$
fnc_name
=
$
func_list
;
$
fnc_name
=
preg_replace
(
'/^\\\\*/'
,
'\\'
,
$
fnc_name
)
;
$
option_value
=
;
preg_match
(
'/^(.*?)(?:\\((.*)\\))?$/s'
,
$
fnc_name
,
$
matched
)
;
if
(
array_key_exists
(
1
,
$
matched
)
)
{
$
fnc_name
=
@
$
matched
[
1
]
;
}
if
(
array_key_exists
(
2
,
$
matched
)
)
{
$
option_value
=
@
$
matched
[
2
]
;
}
unset
(
$
matched
)
;
if
(
strlen
(
trim
(
$
option_value
)
)
)
{
$
option_value
=
json_decode
(
$
option_value
)
;
}
else
{
$
option_value
=
;
}
// var_dump($fnc_name);
// var_dump($option_value);
$
this
->
proc_num
++
;
if
(
@
!
strlen
(
$
this
->
proc_id
)
)
{
$
this
->
proc_id
=
$
this
->
proc_type
.
'_'
.
$
this
->
proc_num
;
}
array_push
(
$
param_arr
,
$
option_value
)
;
call_user_func_array
(
$
fnc_name
,
$
param_arr
)
;
$
this
->
proc_id
=
;
}
elseif
(
is_array
(
$
func_list
)
)
{
foreach
(
$
func_list
as
$
fnc_id
=>
$
fnc_name
)
{
if
(
is_string
(
$
fnc_name
)
)
{
$
fnc_name
=
preg_replace
(
'/^\\\\*/'
,
'\\'
,
$
fnc_name
)
;
}
if
(
is_string
(
$
fnc_id
)
&&
!
preg_match
(
'/^[0-9]+$/'
,
$
fnc_id
)
)
{
$
this
->
proc_id
=
$
fnc_id
;
}
$
param_arr_dd
=
$
param_arr
;
array_unshift
(
$
param_arr_dd
,
$
fnc_name
)
;
call_user_func_array
(
array
(
$
this
,
'fnc_call_plugin_funcs'
)
,
$
param_arr_dd
)
;
}
}
unset
(
$
fnc_name
)
;
}
return
true
;
}

call plugin functions

@param mixed $func_list List of plugins function
@return bool 成功時 `true`、失敗時 `false`


public function draw($data) {

        // if the data is sane, and the widths have been set (if not calculate them)
        if ($this->dataCheck($data)) {

            $barStyle = new Style();

            // set the colors to the bar text and fill
            $barStyle->setColors($this->barText, $this->barFill);

            $bodyStyle = new Style();

            // set the colors to the body text and fill
            $bodyStyle->setColors($this->bodyText, $this->bodyFill);

            // calculate the widths
            $this->calculateWidths($data);

            // calculate the total width
            $totalWidth = $this->calcTotalWidth();

            // if at least one of the columns has header text
            if ($this->hasHeader()) {

                $headers = $this->getHeaderText();

                // if a title was specified
                if ($this->title) {

                    // center the title
                    $justifiedText = $this->clio->justify($this->title, "center", $totalWidth);

                    // create a title style
                    $titleStyle = new Style();
                    $titleStyle->setBold()->setTextColor($this->bodyText);

                    // ask Clio to draw it
                    $this->clio->style($titleStyle)->display($justifiedText)->clear()->newLine();
                }

                // draw the row of cells
                $this->drawRow($headers, $barStyle);

            }

            // go through each row of data
            for ($row = 0; $row<count($data); ++$row) {

                // draw the row of cells
                $this->drawRow($data[$row], $bodyStyle);

            }

            // if the last line is desired
            if ($this->showBottomLine) {

                // now add an empty line
                $emptyLine = str_pad("",$totalWidth);

                // underline it to create a bottom line with the bar fill
                $underline = (new Style())->setUnderscore()->setColors($this->barFill, $this->bodyFill);

                // ask Clio to display it
                $this->clio->style($underline)->display($emptyLine);
            }

        }

    }


public function calculate(FormulasInterface $formula): Calculator
    {
        $formula
            ->using($this->dataSet)
            ->knowing($this->results)
            ->calculate();

        $this->results->save($formula);

        return $this;
    }

public function calculate ( FormulasInterface $ formula ) : Calculator { $ formula -> using ( $ this -> dataSet ) -> knowing ( $ this -> results ) -> calculate ( ) ; $ this -> results -> save ( $ formula ) ; return $ this ; }

Starts a new calculus using the formula sent.
It resets the calculus by emptying the history of calls

@param FormulasInterface $formula
@return Calculator

Starts a new calculus using the formula sent . It resets the calculus by emptying the history of calls


public function hasLayout()
    {
        $masterRequest = $this->requestStack->getMasterRequest();
        $currentRequest = $this->requestStack->getCurrentRequest();

        if (
            $masterRequest->isXmlHttpRequest()
            || 'off' === $masterRequest->get('_layout')
            || (
                $currentRequest !== $masterRequest
                && !$currentRequest->attributes->has('exception')
                && !$currentRequest->attributes->get('_layout', false)
            )
        ) {
            return false;
        }
        return true;
    }

public function hasLayout ( ) { $ masterRequest = $ this -> requestStack -> getMasterRequest ( ) ; $ currentRequest = $ this -> requestStack -> getCurrentRequest ( ) ; if ( $ masterRequest -> isXmlHttpRequest ( ) || 'off' === $ masterRequest -> get ( '_layout' ) || ( $ currentRequest !== $ masterRequest && ! $ currentRequest -> attributes -> has ( 'exception' ) && ! $ currentRequest -> attributes -> get ( '_layout' , false ) ) ) { return false ; } return true ; }

See if the layout should be enabled.

@return bool


public function initialize(TerminalStateInterface $state) {

        // both bold and underscore will have a value of true or false (not undefined
        $this->setBold($state->isBold());
        $this->setUnderscore($state->isUnderscore());

        // for colors, if the color is not valid, then it will stay undefined in this context

        // get the text color
        $textColor = $state->getTextColor();

        // if the text color is valid
        if ($textColor->isValid()) {

            // set it
            $this->setTextColor($textColor);

        } else {

            // the text color is not valid, null out the text color
            $this->setTextColor(null);
        }

        // get the fill color
        $fillColor = $state->getFillColor();

        // if the fill color is valid
        if ($fillColor->isValid()) {

            // set it
            $this->setFillColor($fillColor);

        } else {

            // the fill color is not valid, null out the fill color
            $this->setFillColor(null);
        }

        // chaining
        return $this;

    }

Initialize a style to the state of a terminal

@param TerminalStateInterface $state
@return $this


public function overrideMembersTo(StyleInterface $style) {

        // text color
        $styleTextColor = $style->getTextColor();

        // only change if there is a text color set
        if ($styleTextColor) {

            // clone the text color
            $this->textColor = clone $styleTextColor;
        }

        // fill color
        $styleFillColor = $style->getFillColor();

        // only change if there is a fill color set
        if ($styleFillColor) {

            // clone the fill color
            $this->fillColor = clone $styleFillColor;
        }

        // font styling

        // get the overriding bold
        $bold = $style->getBold();

        // only change the bold, if it is set to something
        if (!is_null($bold)) {

            // save the new bold state
            self::setBold($bold);

        }

        // get the overriding underscore
        $underscore = $style->getUnderscore();

        // only change the underscore, if it is set to something
        if (!is_null($underscore)) {

            // save the new underscore state
            self::setUnderscore($underscore);
        }

        // chaining
        return $this;
    }

Override a style, if anything is set to null, then don't change the value of the recipient object

@param StyleInterface $style
@return $this

Override a style if anything is set to null then don t change the value of the recipient object


public function clearStyling() {

        // reset the colors to null
        $this->textColor = $this->fillColor = null;

        // reset the underscore and bold to false
        $this->underscore = $this->bold = null;

        // chaining
        return $this;
    }


public function setTextColor($color) {

        // if it is null, just remember null
        if (is_null($color)) {

            // undefined
            $this->textColor = null;

        // it is an instance of Color
        } elseif ($color instanceof Color) {

            // clone it
            $this->textColor = clone $color;

        // it is some other type
        } else {

            // let the Color object sort it out
            $this->textColor = new Color($color);

        }

        // chaining
        return $this;

    }

public
function
setTextColor
(
$
color
)
{
// if it is null, just remember null
if
(
is_null
(
$
color
)
)
{
// undefined
$
this
->
textColor
=
;
// it is an instance of Color
}
elseif
(
$
color
instanceof
Color
)
{
// clone it
$
this
->
textColor
=
clone
$
color
;
// it is some other type
}
else
{
// let the Color object sort it out
$
this
->
textColor
=
new
Color
(
$
color
)
;
}
// chaining
return
$
this
;
}

Set the text color

@param Color | string | int | array $color
- Color - a Color object
- String - a W3C color index name "darkblue"
- integer - a number between 0-255 for the XTerm escape code
- array - RGB values in the format [R,G,B]
@return $this


public function setFillColor($color) {

        // if it is null, just remember null
        if (is_null($color)) {

            // undefined
            $this->fillColor = null;

        // if it is an instance of a color
        } elseif ($color instanceof Color) {

            // clone it
            $this->fillColor = clone $color;

        } else
        {

            // it is something else, let the Color object sort it out
            $this->fillColor = new Color($color);

        }

        // chaining
        return $this;
    }

Set the fill color

@param Color | string | int | array $color
- Color - a Color object
- string - a W3C color index name "darkblue"
- integer - a number between 0-255 for the XTerm escape code
- array - RGB values in the format [R,G,B]
@return $this


public function setColors($textColor, $fillColor) {

        // set the text color
        self::setTextColor($textColor);

        // set the fill color
        self::setFillColor($fillColor);

        // chaining
        return $this;
    }

public
function
setColors
(
$
textColor
,
$
fillColor
)
{
// set the text color
self
::
setTextColor
(
$
textColor
)
;
// set the fill color
self
::
setFillColor
(
$
fillColor
)
;
// chaining
return
$
this
;
}

Set both text and fill colors

@param Color | string | int | array $textColor
@param Color | string | int | array $fillColor
- String - a W3C color index name "darkblue"
- integer - a number between 0-255 for the XTerm escape code
- array - RGB values in the format [R,G,B]
@return $this


public function reverseColors() {

        // switch them
        $text = $this->textColor;
        $this->textColor = $this->fillColor;
        $this->fillColor = $text;

        return $this;
    }

public
function
reverseColors
(
)
{
// switch them
$
text
=
$
this
->
textColor
;
$
this
->
textColor
=
$
this
->
fillColor
;
$
this
->
fillColor
=
$
text
;
return
$
this
;
}

Switch the text and fill colors

@return $this


public static function factory($function)
    {
        $function = (string)$function;
        if (!isset(self::$functions[$function]))
            self::$functions[$function] = new self($function);
        return self::$functions[$function];
    }

public static function factory ( $ function ) { $ function = ( string ) $ function ; if ( ! isset ( self :: $ functions [ $ function ] ) ) self :: $ functions [ $ function ] = new self ( $ function ) ; return self :: $ functions [ $ function ] ; }

Constructs a new ReflectionFunction object from function name and store it in cache.
If object already exists in cache it will taken from there instead of creating
new object

@param string $class
@return ReflectionFunction

Constructs a new ReflectionFunction object from function name and store it in cache . If object already exists in cache it will taken from there instead of creating new object


public function loadPlugins()
    {
        $this->checkCache();
        $this->validatePlugins();
        $this->countPlugins();

        foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) {
            include_once(WPMU_PLUGIN_DIR . '/' . $plugin_file);
        }

        $this->pluginHooks();
    }

public function loadPlugins ( ) { $ this -> checkCache ( ) ; $ this -> validatePlugins ( ) ; $ this -> countPlugins ( ) ; foreach ( self :: $ cache [ 'plugins' ] as $ plugin_file => $ plugin_info ) { include_once ( WPMU_PLUGIN_DIR . '/' . $ plugin_file ) ; } $ this -> pluginHooks ( ) ; }

Run some checks then autoload our plugins.

Run some checks then autoload our plugins .


public function showInAdmin($show, $type)
    {
        $screen = get_current_screen();
        $current = is_multisite() ? 'plugins-network' : 'plugins';

        if ($screen->{'base'} != $current || $type != 'mustuse' || !current_user_can('activate_plugins')) {
            return $show;
        }

        $this->updateCache();

        self::$auto_plugins = array_map(function ($auto_plugin) {
            return $auto_plugin;
        }, self::$auto_plugins);

        $GLOBALS['plugins']['mustuse'] = array_unique(array_merge(self::$auto_plugins, self::$mu_plugins), SORT_REGULAR);

        return false;
    }

public function showInAdmin ( $ show , $ type ) { $ screen = get_current_screen ( ) ; $ current = is_multisite ( ) ? 'plugins-network' : 'plugins' ; if ( $ screen -> { 'base' } != $ current || $ type != 'mustuse' || ! current_user_can ( 'activate_plugins' ) ) { return $ show ; } $ this -> updateCache ( ) ; self :: $ auto_plugins = array_map ( function ( $ auto_plugin ) { return $ auto_plugin ; } , self :: $ auto_plugins ) ; $ GLOBALS [ 'plugins' ] [ 'mustuse' ] = array_unique ( array_merge ( self :: $ auto_plugins , self :: $ mu_plugins ) , SORT_REGULAR ) ; return false ; }

Filter show_advanced_plugins to display the autoloaded plugins.
@param $bool bool Whether to show the advanced plugins for the specified plugin type.
@param $type string The plugin type, i.e., `mustuse` or `dropins`
@return bool We return `false` to prevent WordPress from overriding our work
{@internal We add the plugin details ourselves, so we return false to disable the filter.}

Filter show_advanced_plugins to display the autoloaded plugins .


private function checkCache()
    {
        $cache = get_site_option('bedrock_autoloader');

        if ($cache === false) {
            $this->updateCache();
            return;
        }

        self::$cache = $cache;
    }

private function checkCache ( ) { $ cache = get_site_option ( 'bedrock_autoloader' ) ; if ( $ cache === false ) { $ this -> updateCache ( ) ; return ; } self :: $ cache = $ cache ; }

This sets the cache or calls for an update


private function updateCache()
    {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');

        self::$auto_plugins = get_plugins(self::$relative_path);
        self::$mu_plugins = get_mu_plugins();
        $plugins = array_diff_key(self::$auto_plugins, self::$mu_plugins);
        $rebuild = !is_array(self::$cache['plugins']);
        self::$activated = ($rebuild) ? $plugins : array_diff_key($plugins, self::$cache['plugins']);
        self::$cache = array('plugins' => $plugins, 'count' => $this->countPlugins());

        update_site_option('bedrock_autoloader', self::$cache);
    }

private function updateCache ( ) { require_once ( ABSPATH . 'wp-admin/includes/plugin.php' ) ; self :: $ auto_plugins = get_plugins ( self :: $ relative_path ) ; self :: $ mu_plugins = get_mu_plugins ( ) ; $ plugins = array_diff_key ( self :: $ auto_plugins , self :: $ mu_plugins ) ; $ rebuild = ! is_array ( self :: $ cache [ 'plugins' ] ) ; self :: $ activated = ( $ rebuild ) ? $ plugins : array_diff_key ( $ plugins , self :: $ cache [ 'plugins' ] ) ; self :: $ cache = array ( 'plugins' => $ plugins , 'count' => $ this -> countPlugins ( ) ) ; update_site_option ( 'bedrock_autoloader' , self :: $ cache ) ; }

Get the plugins and mu-plugins from the mu-plugin path and remove duplicates.
Check cache against current plugins for newly activated plugins.
After that, we can update the cache.

Get the plugins and mu - plugins from the mu - plugin path and remove duplicates . Check cache against current plugins for newly activated plugins . After that we can update the cache .


private function pluginHooks()
    {
        if (!is_array(self::$activated)) {
            return;
        }

        foreach (self::$activated as $plugin_file => $plugin_info) {
            add_action('wp_loaded', function () use ($plugin_file) {
                do_action('activate_' . $plugin_file);
            });
        }
    }

private function pluginHooks ( ) { if ( ! is_array ( self :: $ activated ) ) { return ; } foreach ( self :: $ activated as $ plugin_file => $ plugin_info ) { add_action ( 'wp_loaded' , function ( ) use ( $ plugin_file ) { do_action ( 'activate_' . $ plugin_file ) ; } ) ; } }

This accounts for the plugin hooks that would run if the plugins were
loaded as usual. Plugins are removed by deletion, so there's no way
to deactivate or uninstall.

This accounts for the plugin hooks that would run if the plugins were loaded as usual . Plugins are removed by deletion so there s no way to deactivate or uninstall .


public function channel($name)
    {
        if (array_key_exists($name, $this->channels)) {
            return $this->channels[$name];
        }

        return null;
    }

public function channel ( $ name ) { if ( array_key_exists ( $ name , $ this -> channels ) ) { return $ this -> channels [ $ name ] ; } return null ; }

Get monolog instance for a specific channel

@param  string $name Channel name
@return \Monolog\Logger|null


private function initLoggers(array $loggers)
    {
        foreach ($loggers as $channel => $config) {
            $this->createLogger($channel, $config);
        }
    }

private function initLoggers ( array $ loggers ) { foreach ( $ loggers as $ channel => $ config ) { $ this -> createLogger ( $ channel , $ config ) ; } }

Read config array and initialize
all loggers

@param  array  $loggers
@return void


private function createLogger($channel, array $config)
    {
        // Setup configuration
        // Use default laravel logs path
        $storagePath = $this->app->make('path.storage');
        $filepath = $storagePath . '/logs/' . $config['stream'];

        $logger = new Logger($channel);
        $handler = new StreamHandler($filepath);

        // Daily rotation
        if ($config['daily']) {
            $handler = new RotatingFileHandler($filepath, 1);
        }

        // Format line
        if (isset($config['format'])) {
            $format = $config['format'];
            $handler->setFormatter(new LineFormatter($format['output'], $format['date']));
        }

        $logger->pushHandler($handler);

        $this->channels[$channel] = $logger;
    }

private
function
createLogger
(
$
channel
,
array
$
config
)
{
// Setup configuration
// Use default laravel logs path
$
storagePath
=
$
this
->
app
->
make
(
'path.storage'
)
;
$
filepath
=
$
storagePath
.
'/logs/'
.
$
config
[
'stream'
]
;
$
logger
=
new
Logger
(
$
channel
)
;
$
handler
=
new
StreamHandler
(
$
filepath
)
;
// Daily rotation
if
(
$
config
[
'daily'
]
)
{
$
handler
=
new
RotatingFileHandler
(
$
filepath
,
1
)
;
}
// Format line
if
(
isset
(
$
config
[
'format'
]
)
)
{
$
format
=
$
config
[
'format'
]
;
$
handler
->
setFormatter
(
new
LineFormatter
(
$
format
[
'output'
]
,
$
format
[
'date'
]
)
)
;
}
$
logger
->
pushHandler
(
$
handler
)
;
$
this
->
channels
[
$
channel
]
=
$
logger
;
}

Create new logger instance with given
configuration and store it in array
with channel name

@param  string $channel Channel name
@param  array $config  Channel configuration
@return void


public function getObjectsAction()
    {
        $qb = $this->getQueryBuilder();
        $qb->select(\CampaignChain\CoreBundle\Controller\REST\LocationController::SELECT_STATEMENT);
        $qb->from('CampaignChain\CoreBundle\Entity\Location', 'l');
        $qb->where('l.channel IS NULL');
        $qb->orderBy('l.name');
        $qb = $this->getModuleRelation($qb, 'l.locationModule', self::MODULE_URI);
        $qb = $this->getLocationChannelId($qb);
        $query = $qb->getQuery();

        return $this->response(
            $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)
        );
    }

Get a list of eZ Platform content object Locations.

Example Request
===============

GET /api/{version}/p/campaignchain/location-ezplatform/objects

Example Response
================
{
"response": [
{
"id": 108,
"identifier": "62",
"name": "eZ Publish Tutorials",
"status": "unpublished",
"createdDate": "2015-12-01T09:37:39+0000",
"operationId": "92",
"channelId": "8"
}
]
}

@ApiDoc(
section="Packages: eZ Platform"
)

Get a list of eZ Platform content object Locations .


public static function factory($class)
    {
        if (is_object($class))
            $class = get_class($class);
        $class = (string)$class;
        if (!isset(self::$classes[$class]))
            self::$classes[$class] = new self($class);
        return self::$classes[$class];
    }

public static function factory ( $ class ) { if ( is_object ( $ class ) ) $ class = get_class ( $ class ) ; $ class = ( string ) $ class ; if ( ! isset ( self :: $ classes [ $ class ] ) ) self :: $ classes [ $ class ] = new self ( $ class ) ; return self :: $ classes [ $ class ] ; }

Constructs a new ReflectionClass object from class name and store it in cache.
If object already exists in cache it will taken from there instead of creating
new object

@param string|object $class
@return ReflectionClass

Constructs a new ReflectionClass object from class name and store it in cache . If object already exists in cache it will taken from there instead of creating new object


public function getInterfaces()
    {
        $interfaceNames = $this->getInterfaceNames();
        $interfaces = array();
        foreach ($interfaceNames as $interface)
            $interfaces[$interface] = ReflectionClass::factory($interface);
        return $interfaces;
    }

public function getInterfaces ( ) { $ interfaceNames = $ this -> getInterfaceNames ( ) ; $ interfaces = array ( ) ; foreach ( $ interfaceNames as $ interface ) $ interfaces [ $ interface ] = ReflectionClass :: factory ( $ interface ) ; return $ interfaces ; }

Get interfaces ReflectionObjects implemented by class

@return array


public function getParentClass()
    {
        $parentClass = parent::getParentClass();
        if ($parentClass) {
            return ReflectionClass::factory($parentClass->getName());
        }
        return false;
    }

public function getParentClass ( ) { $ parentClass = parent :: getParentClass ( ) ; if ( $ parentClass ) { return ReflectionClass :: factory ( $ parentClass -> getName ( ) ) ; } return false ; }

Get parent ReflectionClass object

@return ReflectionClass|false


public function getMethods($filter = null)
    {
        $args = func_get_args();
        $methods = ReflectionMethod::factory($this->name);

        if (count($args)) {
            return $this->filter($methods, current($args));
        }

        return $methods;
    }

public function getMethods ( $ filter = null ) { $ args = func_get_args ( ) ; $ methods = ReflectionMethod :: factory ( $ this -> name ) ; if ( count ( $ args ) ) { return $ this -> filter ( $ methods , current ( $ args ) ) ; } return $ methods ; }

Get class ReflectionMethods objects array list.

@return array

Get class ReflectionMethods objects array list .


public function getProperties($filter = null)
    {
        $args = func_get_args();
        $properties = ReflectionProperty::factory($this->name);

        if (count($args)) {
            return $this->filter($properties, current($args));
        }

        return $properties;
    }

public function getProperties ( $ filter = null ) { $ args = func_get_args ( ) ; $ properties = ReflectionProperty :: factory ( $ this -> name ) ; if ( count ( $ args ) ) { return $ this -> filter ( $ properties , current ( $ args ) ) ; } return $ properties ; }

Get class ReflectionProperty objects array list.

@return array

Get class ReflectionProperty objects array list .


public function is( $type ) {
		switch ( $type ) {
			case 'admin':
				return is_admin();
			case 'ajax':
				return defined( 'DOING_AJAX' );
			case 'cron':
				return defined( 'DOING_CRON' );
			case 'frontend':
				return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) && ! defined( 'REST_REQUEST' );
		}
	}

public function is ( $ type ) { switch ( $ type ) { case 'admin' : return is_admin ( ) ; case 'ajax' : return defined ( 'DOING_AJAX' ) ; case 'cron' : return defined ( 'DOING_CRON' ) ; case 'frontend' : return ( ! is_admin ( ) || defined ( 'DOING_AJAX' ) ) && ! defined ( 'DOING_CRON' ) && ! defined ( 'REST_REQUEST' ) ; } }

What type of request is this?

@param  string $type admin, ajax, cron or frontend.
@return bool


public function addStyle(MaterializedResource $resource, $mediaType = 'all')
    {
        $this->styles[$resource->getPath()] = array(
            'resource' => $resource,
            'content' => $resource->getContent(),
            'media' => $mediaType,
        );
    }

public function addStyle ( MaterializedResource $ resource , $ mediaType = 'all' ) { $ this -> styles [ $ resource -> getPath ( ) ] = array ( 'resource' => $ resource , 'content' => $ resource -> getContent ( ) , 'media' => $ mediaType , ) ; }


public function getAggregateStyle()
    {
        $styles = $this->rewritePaths($this->styles);
        $styles = $this->wrapMediaRules($styles);
        $content = $this->concatenateStyles($styles);
        $content = $this->moveImportsToStart($content);
        return $content;
    }

public function getAggregateStyle ( ) { $ styles = $ this -> rewritePaths ( $ this -> styles ) ; $ styles = $ this -> wrapMediaRules ( $ styles ) ; $ content = $ this -> concatenateStyles ( $ styles ) ; $ content = $ this -> moveImportsToStart ( $ content ) ; return $ content ; }


protected function rewritePaths(array $styles)
    {
        foreach ($styles as &$style) {
            /** @var $resource MaterializedResource */
            $resource = $style['resource'];
            $replaceCallback = function ($match) use ($resource) {
                return "url('".$resource->resolvePath($match[1])."')";
            };
            $style['content'] = preg_replace_callback(ResourceScanner::PATH_PATTERN, $replaceCallback, $style['content']);
        }
        return $styles;
    }

Rewrites the paths of referenced resources.

Rewrites the paths of referenced resources .


protected function wrapMediaRules(array $styles)
    {
        foreach ($styles as &$style) {
            // Wrap in media rule if a media rule does not already exist in a non-all media style.
            if ($style['media'] != 'all' && strpos($style['content'], '@media') === false) {
                $style['content'] = '@media '.$style['media'].' {'.$style['content'].'}';
            }
        }
        return $styles;
    }

Wraps resource content in media rules where appropriate.

Wraps resource content in media rules where appropriate .


protected function moveImportsToStart($content)
    {
        $imports = '';
        $replaceCallback = function ($match) use (&$imports) {
            $imports .= $match[0];
            return '';
        };
        $content = preg_replace_callback('/@import[^;]+;/i', $replaceCallback, $content);
        $content = $imports.$content;
        return $content;
    }

protected function moveImportsToStart ( $ content ) { $ imports = '' ; $ replaceCallback = function ( $ match ) use ( & $ imports ) { $ imports .= $ match [ 0 ] ; return '' ; } ; $ content = preg_replace_callback ( '/@import[^;]+;/i' , $ replaceCallback , $ content ) ; $ content = $ imports . $ content ; return $ content ; }

Moves import rules to the start of the style sheet.

Moves import rules to the start of the style sheet .