<?php

/*
 * This file is part of the Active Collab DatabaseObject project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseObject;

use ActiveCollab\DatabaseConnection\ConnectionInterface;
use ActiveCollab\DatabaseConnection\Result\ResultInterface;
use ActiveCollab\Etag\EtagInterface\Implementation as EtagInterfaceImplementation;
use LogicException;
use Psr\Log\LoggerInterface;

/**
 * @package ActiveCollab\DatabaseObject
 */
abstract class Collection implements CollectionInterface
{
    use EtagInterfaceImplementation;

    /**
     * @var ConnectionInterface
     */
    protected $connection;

    /**
     * @var PoolInterface
     */
    protected $pool;

    /**
     * @var LoggerInterface
     */
    protected $log;

    /**
     * @param ConnectionInterface  $connection
     * @param PoolInterface        $pool
     * @param LoggerInterface|null $log
     */
    public function __construct(ConnectionInterface &$connection, PoolInterface &$pool, LoggerInterface &$log = null)
    {
        $this->connection = $connection;
        $this->pool = $pool;
        $this->log = $log;

        $this->configure();
    }

    /**
     * Pre-configure the collection when it is created.
     */
    protected function configure()
    {
    }

    /**
     * Return true if ready.
     *
     * If collection declares that it is not ready, but execute methods get called, we should throw an exception
     *
     * @return bool
     */
    protected function isReady()
    {
        return true;
    }

    /**
     * @var string
     */
    private $application_identifier = 'APPv1.0';

    /**
     * Return application identifier.
     *
     * @return string
     */
    public function getApplicationIdentifier()
    {
        return $this->application_identifier;
    }

    /**
     * Set application identifier.
     *
     * @param  string $value
     * @return $this
     */
    public function &setApplicationIdentifier($value)
    {
        $this->application_identifier = $value;

        return $this;
    }

    /**
     * Prepare collection tag from bits of information.
     *
     * @param  string $additional_identifier
     * @param  string $visitor_identifier
     * @param  string $hash
     * @return string
     */
    protected function prepareTagFromBits($additional_identifier, $visitor_identifier, $hash)
    {
        return implode(',', [$this->getApplicationIdentifier(), 'collection', get_class($this), $additional_identifier, $visitor_identifier, $hash]);
    }

    /**
     * Return true if this object can be tagged and cached on client side.
     *
     * @return bool|null
     */
    public function canBeTagged()
    {
        return true;
    }

    // ---------------------------------------------------
    //  Pagination
    // ---------------------------------------------------

    /**
     * Set pagination configuration.
     *
     * @param  int   $current_page
     * @param  int   $items_per_page
     * @return $this
     */
    public function &pagination($current_page = 1, $items_per_page = 100)
    {
        $this->is_paginated = true;

        $this->currentPage($current_page);

        $this->items_per_page = (int) $items_per_page;

        if ($this->items_per_page < 1) {
            $this->items_per_page = 100;
        }

        return $this;
    }

    /**
     * @var bool
     */
    private $is_paginated = false;

    /**
     * Return true if collection is paginated.
     *
     * @return bool
     */
    public function isPaginated()
    {
        return $this->is_paginated;
    }

    /**
     * @var int|null
     */
    private $current_page = null;

    /**
     * @var int|null
     */
    private $items_per_page = null;

    /**
     * Set current page.
     *
     * @param  int   $value
     * @return $this
     */
    public function &currentPage($value)
    {
        if (!$this->is_paginated) {
            throw new LogicException('Page can be set only for paginated collections');
        }

        $this->current_page = (int) $value;

        if ($this->current_page < 1) {
            $this->current_page = 1;
        }

        return $this;
    }

    /**
     * Return current page #.
     *
     * @return int|null
     */
    public function getCurrentPage()
    {
        return $this->current_page;
    }

    /**
     * Return number of items that are displayed per page.
     *
     * @return int|null
     */
    public function getItemsPerPage()
    {
        return $this->items_per_page;
    }

    /**
     * Return array or property => value pairs that describes this object.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        $result = $this->execute();

        if ($result instanceof ResultInterface) {
            return $result->jsonSerialize();
        } elseif ($result === null) {
            return [];
        } else {
            return $result;
        }
    }
}


<?php

namespace Mamikon\RoleManager\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mamikon\RoleManager\Models\Permissions;
use Mamikon\RoleManager\Requests\PermissionRequest;

/**
 * Resource Class for Permissions
 *
 * @category Laravel_Package
 * @package  Mamikon\RoleManager
 * @author   Mamikon Arakelyan <m.araqelyan@gmail.com>
 * @license  https://github.com/mamikon/role-manager/blob/master/LICENSE.md MIT
 * @link     https://github.com/mamikon/role-manager
 */

class PermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('view_permission');
        if (!empty($request->term)) {
            $term = trim($request->term);
            $permissions = Permissions::where('name', 'like', '%' . $term . '%')
                ->orWhere('description', 'like', '%' . $term . '%')
                ->orWhere('class', 'like', '%' . $term . '%')
                ->orWhere('method', 'like', '%' . $term . '%')
                ->paginate(config('roleManager.permissionsPerPage'));

        } else {
            $permissions = Permissions::paginate(
                config('roleManager.permissionsPerPage')
            );

        }
        return view(
            "RoleManager::permission.index",
            ['permissions' => $permissions]
        );
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create_permission');
        return view('RoleManager::permission.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request|PermissionRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(PermissionRequest $request)
    {
        $this->authorize('create_permission');
        $permission = Permissions::create($request->all());
        $request->session()->flash('message', 'Permission Successfully Created');
        return redirect()->route('RoleManager::permission.edit', $permission->id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int|Permissions $permission
     *
     * @return \Illuminate\Http\Response
     */
    public function edit(Permissions $permission)
    {
        $this->authorize('edit_permission');
        return view('RoleManager::permission.edit', ['permission' => $permission]);
    }

    /**
     * Update the permission in storage.
     *
     * @param Request|PermissionRequest $request
     * @param int                       $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(PermissionRequest $request, $id)
    {
        $this->authorize('edit_permission');
        $permission = Permissions::where('id', $id)->firstOrFail();
        $permission->update($request->all());
        $request->session()->flash('message', 'Permission Updated Successfully');
        return redirect()->route('RoleManager::permission.edit', $permission->id);
    }

    /**
     * Remove the permission from storage.
     *
     * @param int $id Permission Id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('delete_permission');
        Permissions::where('id', $id)->delete();
        session()->flash('message', 'Permission Deleted Successfully');
        session()->flash('message-status', 'alert-info');
        return redirect()->route('RoleManager::permission.index');
    }
}


<?php

namespace Adback\ApiClient\Driver;

/**
 * Class MysqliScriptCache
 */
class MysqliScriptCache extends SqlScriptCache implements ScriptCacheInterface
{
    protected $connection;

    /**
     * @param mixed $connection Mysqli Connection
     */
    public function __construct($connection)
    {
        $this->connection = $connection;
    }

    /**
     * @param string $key
     *
     * @return string|null
     */
    protected function get($key)
    {
        $value = null;
        $request = $this->connection->prepare('SELECT our_value FROM adback_cache_table WHERE our_key = ? LIMIT 1');
        $request->bind_param('s', $key);

        $request->execute();
        $request->bind_result($value);
        $request->fetch();
        $request->free_result();

        return $value;
    }

    /**
     * @param string $key
     * @param string $value
     */
    protected function set($key, $value)
    {
        $this->clear($key);
        $request = $this->connection->prepare("INSERT INTO adback_cache_table (our_key, our_value) VALUES (?, ?)");
        $request->bind_param('ss', $key, $value);
        $request->execute();
    }

    /**
     * @param string $key
     */
    protected function clear($key)
    {
        $request = $this->connection->prepare("DELETE FROM adback_cache_table WHERE our_key = ?");
        $request->bind_param('s', $key);
        $request->execute();
    }
}


<?php

/*
 * doctrine-base-repositories (https://github.com/juliangut/doctrine-base-repositories).
 * Doctrine2 utility repositories.
 *
 * @license MIT
 * @link https://github.com/juliangut/doctrine-base-repositories
 * @author Julián Gutiérrez <juliangut@gmail.com>
 */

declare(strict_types=1);

namespace Jgut\Doctrine\Repository;

use Zend\Paginator\Adapter\AdapterInterface;
use Zend\Paginator\Paginator;

/**
 * Pagination trait.
 */
trait PaginatorTrait
{
    /**
     * Get configured paginator.
     *
     * @param AdapterInterface $adapter
     * @param int              $itemsPerPage
     *
     * @return Paginator
     */
    protected function getPaginator(AdapterInterface $adapter, int $itemsPerPage): Paginator
    {
        $paginator = new Paginator($adapter);
        $paginator->setItemCountPerPage(max(-1, $itemsPerPage));

        return $paginator;
    }

    /**
     * Return paginated elements filtered by criteria or throw an exception if none found.
     *
     * @param array      $criteria
     * @param array|null $orderBy
     * @param int        $itemsPerPage
     *
     * @throws FindException
     *
     * @return Paginator
     */
    public function findPaginatedByOrFail(array $criteria, array $orderBy = null, int $itemsPerPage = 10): Paginator
    {
        $paginator = $this->findPaginatedBy($criteria, $orderBy, $itemsPerPage);

        if ($paginator->count() === 0) {
            throw new FindException('FindPaginatedBy did not return any results');
        }

        return $paginator;
    }

    /**
     * Return paginated elements filtered by criteria.
     *
     * @param array      $criteria
     * @param array|null $orderBy
     * @param int        $itemsPerPage
     *
     * @return Paginator
     */
    abstract public function findPaginatedBy($criteria, array $orderBy = null, int $itemsPerPage = 10): Paginator;
}


<?php
/**
 * Copyright © OXID eSales AG. All rights reserved.
 * See LICENSE file for license details.
 */

namespace OxidEsales\EcondaTrackingComponent\File;

use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem as SymfonyFileSystem;

/**
 * Class responsible for file system actions.
 */
class FileSystem
{
    private $filesystem;

    /**
     * @param SymfonyFileSystem $filesystem
     */
    public function __construct(SymfonyFileSystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * @param string $pathToDirectory
     *
     * @return bool
     */
    public function createDirectory($pathToDirectory): bool
    {
        try {
            $this->filesystem->mkdir($pathToDirectory);
            return true;
        } catch (IOException $exception) {
            return false;
        }
    }

    /**
     * @param string $path
     * @return bool
     */
    public function isWritable(string $path): bool
    {
        return is_writable($path);
    }

    /**
     * @param string $path
     *
     * @return bool
     */
    public function isFilePresent(string $path): bool
    {
        return $this->filesystem->exists($path);
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.2
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl;

use Antares\Foundation\Support\Providers\ModuleServiceProvider;
use Antares\Acl\Http\Handlers\GroupsBreadcrumbMenu;
use Antares\Acl\Http\Handlers\UsersBreadcrumbMenu;
use Antares\Acl\Http\Handlers\ModulesPane;
use Antares\Acl\Http\Handlers\ControlPane;
use Antares\Acl\Http\Handlers\StaffPane;

class AclServiceProvider extends ModuleServiceProvider
{

    /**
     * The application or extension namespace.
     *
     * @var string|null
     */
    protected $namespace = 'Antares\Acl\Http\Controllers';

    /**
     * The application or extension group namespace.
     *
     * @var string|null
     */
    protected $routeGroup = 'antares/acl';

    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [];

    /**
     * Register service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->bindContracts();
    }

    /**
     * Boot extension components.
     *
     * @return void
     */
    protected function bootExtensionComponents()
    {
        $path = __DIR__ . '/../resources';
        $this->addConfigComponent('antares/acl', 'antares/acl', "{$path}/config");
        $this->addLanguageComponent('antares/acl', 'antares/acl', "{$path}/lang");
        $this->addViewComponent('antares/acl', 'antares/acl', "{$path}/views");
        $this->bootMenu();
        $this->bootMemory();
    }

    /**
     * Boot extension routing.
     *
     * @return void
     */
    protected function loadRoutes()
    {
        $path = __DIR__;

        $this->loadBackendRoutesFrom("{$path}/Http/backend.php");
    }

    /**
     * booting menu
     */
    protected function bootMenu()
    {
        $view = $this->app->make('view');
        $view->composer('antares/acl::acl.*', function () {
            return ModulesPane::getInstance()->make();
        });
        $this->attachMenu([GroupsBreadcrumbMenu::class, UsersBreadcrumbMenu::class]);
        $view->composer('antares/foundation::settings.*', ControlPane::class);
        $view->composer('antares/acl::*', StaffPane::class);
    }

    /**
     * booting acl memory
     */
    protected function bootMemory()
    {
        $this->app->make('antares.acl')->make($this->routeGroup)->attach(
                $this->app->make('antares.platform.memory')
        );
    }

}


<?php

namespace Mamikon\RoleManager;

use Illuminate\Support\Facades\Request;
use \Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use Mamikon\RoleManager\Commands\RoleMangerCommand;

/**
 * Class RoleManagerProvider
 *
 * @category Laravel_Package
 * @package  Mamikon\RoleManager
 * @author   Mamikon Arakelyan <m.araqelyan@gmail.com>
 * @license  https://github.com/mamikon/role-manager/blob/master/LICENSE.md MIT
 * @link     https://github.com/mamikon/role-manager
 */
class RoleManagerProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->_extendedValidation();
        $this->_loadParts();
        $this->_publish();

        $roleManager = new RoleManager();
        $roleManager->defineAllPermissions();
        $this->app->instance('Mamikon\RoleManager', $roleManager);
        if ($this->app->runningInConsole()) {
            $this->commands(
                [RoleMangerCommand::class,]
            );
        }

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/config.php', 'roleManager.php'
        );
    }

    /**
     * Publish package Components
     *
     * @return void
     */
    private function _publish()
    {
        $this->publishes(
            [
                __DIR__ . '/config.php' => config_path('roleManager.php'),
            ]
        );

        $this->publishes(
            [
                __DIR__ . '/views' => resource_path('views/vendor/RoleManager'),
            ]
        );
    }

    /**
     * Load Package Components
     *
     * @return void
     */
    private function _loadParts()
    {
        $this->loadRoutesFrom(__DIR__ . '/routes.php');
        $this->loadMigrationsFrom(__DIR__ . '/migrations');
        $this->loadTranslationsFrom(__DIR__ . '/translations', 'RoleManager');
        $this->loadViewsFrom(__DIR__ . '/views', 'RoleManager');
    }

    /**
     * Add new Validation Types
     *
     * @return void
     */
    private function _extendedValidation()
    {
        Validator::extend(
            'classExist', function ($attribute, $value, $parameters, $validator) {
                if (empty($value)) {
                    return true;
                }
                return class_exists($value);
            }
        );
        Validator::extend(
            'methodExist', function ($attribute, $value, $parameters, $validator) {
                if (!empty(Request::input('class'))) {
                    return method_exists(Request::input('class'), $value);
                }
                return true;
            }
        );

        Validator::replacer(
            'classExist',
            function ($message, $attribute, $rule, $parameters) {
                return "Class does not exist";
            }
        );
        Validator::replacer(
            'methodExist',
            function ($message, $attribute, $rule, $parameters) {
                return
                    "Method in "
                    . Request::input('class')
                    . " class does not exist.";
            }
        );
    }
}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class PageflowerPageflowDebugCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('pageflower:pageflow:debug')
            ->setDescription('Displays current pageflows for an application')
            ->setHelp(
'The <info>%command.name%</info> displays the configured pageflows:'.PHP_EOL.
PHP_EOL.
'  <info>php %command.full_name%</info>'
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $pageflows = $this->getContainer()->get('phpmentors_pageflower.pageflow_repository')->findAll();

        $output->writeln($this->getHelper('formatter')->formatSection('pageflower', 'Pageflows'));

        $pageflowIdMaxLength = strlen('pageflowId');

        foreach ($pageflows as $pageflowId => $pageflow) {
            $pageflowIdMaxLength = max($pageflowIdMaxLength, strlen($pageflowId));
        }

        $format = '%-'.$pageflowIdMaxLength.'s';
        $formatHeader = '%-'.($pageflowIdMaxLength + 19).'s';
        $output->writeln(sprintf($formatHeader, '<comment>Pageflow Id</comment>'));

        foreach ($pageflows as $pageflowId => $pageflow) {
            $output->writeln(sprintf($format, $pageflowId), OutputInterface::OUTPUT_RAW);
        }
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Http\Handlers;

use Antares\Foundation\Http\Composers\LeftPane;

class StaffPane extends LeftPane
{

    /**
     * Handle pane for dashboard page.
     *
     * @return void
     */
    public function compose($name = null, $options = array())
    {
        $menu                 = app('antares.widget')->make('menu.acl.staff.pane');
        $acl                  = app('antares.acl')->make('antares/acl');
        $canAdministratorList = $acl->can('admin-list');

        $canRoleList = $acl->can('roles-list');
        if (!$canAdministratorList and ! $canRoleList) {
            return;
        }
        if ($canRoleList) {
            $menu->add('groups')
                    ->link(handles('antares::acl/index/roles'))
                    ->title(trans('Groups'))
                    ->icon('zmdi-accounts-list-alt')
                    ->active(!is_null(from_route('roles')) or request()->segment(4) === 'roles' or request()->segment(3) === 'roles');
        }
        if ($canAdministratorList) {
            $menu->add('users')
                    ->link(handles('antares::acl/index/users'))
                    ->title(trans('Users'))
                    ->icon('zmdi-accounts-list')
                    ->active(!is_null(from_route('user')) or request()->segment(4) === 'users' or request()->segment(3) === 'users');
        }
        $pane = app('antares.widget')->make('pane.left');
        $pane->add('control')->content(view('antares/acl::partial._staff_pane'));
    }

}


<?php namespace Magniloquent\Magniloquent;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;

class Magniloquent extends Model {

    /**
     * @var array The rules used to validate the model
     */
    protected static $rules = array(
        'save'   => array(),
        'create' => array(),
        'update' => array()
    );

    /**
     * @var array The attributes to purge before saving
     */
    protected static $purgeable = array();

    /**
     * @var array The relationships this model has to other models
     */
    protected static $relationships = array();

    /**
     * @var array The merged rules created when validating
     */
    protected $mergedRules = array();

    /**
     * @var \Illuminate\Support\MessageBag The errors generated if validation fails
     */
    protected $validationErrors;

    /**
     * @var bool Designates if the model has been saved
     */
    protected $saved = false;

    /**
     * @var bool Designates if the model is valid after validation
     */
    protected $valid = false;

    /**
     * @var array Custom messages when model doesn't pass validation
     */
    protected $customMessages = array();

    /**
     * @var array The attributes needed to be hashed before saving
     */
    protected static $needsHash = array();

    /**
     * The constructor of the model. Takes optional array of attributes.
     * Also, it sets validationErrors to be an empty MessageBag instance.
     *
     * @param array $attributes The attributes of the model to set at instantiation
     */
    public function __construct($attributes = array())
    {
        parent::__construct($attributes);
        $this->validationErrors = new MessageBag;
    }

    /**
     * Handle dynamic method calls into the method.
     *
     * @param  string $method
     * @param  array  $parameters
     *
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        if (array_key_exists($method, static::$relationships))
            return $this->callRelationships($method);

        return parent::__call($method, $parameters);
    }

    /**
     * Dynamically retrieve attributes on the model.
     *
     * @param  string $key
     *
     * @return mixed
     */
    public function __get($key)
    {
        if (array_key_exists($key, static::$relationships))
        {
            // If the relation is already loaded, just return it,
            // otherwise it will query the relation twice.
            if (array_key_exists($key, $this->relations))
            {
                return $this->relations[$key];
            }

            $relation = $this->callRelationships($key);

            return $this->relations[$key] = $relation->getResults();
        }

        return parent::__get($key);
    }

    /**
     * Perform actions before the Model effectively performs the save call.
     *
     * @return void
     */
    public function beforeSave() {}

    /**
     * Prepare before the Model is actually saved
     *
     * @param array $new_attributes New attributes to fill onto the model before saving
     * @param bool  $forceSave      Whether to validate or not. Defaults to validating before saving
     *
     * @return bool
     */
    public function save(array $new_attributes = array(), $forceSave = false)
    {
        $options = array();

        if (array_key_exists('touch', $new_attributes))
        {
            $options['touch'] = $new_attributes['touch'];
            $new_attributes = array_except($new_attributes, array('touch'));
        }

        $this->fill($new_attributes);

        $this->beforeSave();

        if (! $forceSave)
        {
            // If the validation failed, return false
            if (! $this->valid && ! $this->validate())
                return false;
        }

        // Purge unnecessary fields
        $this->purgeUnneeded();

        // Auto hash passwords
        $this->autoHash();

        $this->saved = true;

        return parent::save($options);
    }

    /**
     * Define an inverse one-to-one or many relationship.
     *
     * @param  string $related
     * @param  string $foreignKey
     * @param  string $otherKey
     * @param  string $relation
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relatinoships.
        if (is_null($relation))
        {
            list(, $caller, $backtrace) = debug_backtrace(false);

            if ($backtrace['function'] == 'callRelationships')
            {
                $relation = $backtrace['args'][0];
            }
            else
            {
                $relation = $caller['function'];
            }
        }

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey))
        {
            $foreignKey = snake_case($relation) . '_id';
        }

        $instance = new $related;

        // Once we have the foreign key names, we'll just create a new Eloquent query
        // for the related models and returns the relationship instance which will
        // actually be responsible for retrieving and hydrating every relations.
        $query = $instance->newQuery();

        $otherKey = $otherKey ? : $instance->getKeyName();

        return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
    }

    /**
     * Define an polymorphic, inverse one-to-one or many relationship.
     *
     * @param  string $name
     * @param  string $type
     * @param  string $id
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function morphTo($name = null, $type = null, $id = null)
    {
        // If no name is provided, we will use the backtrace to get the function name
        // since that is most likely the name of the polymorphic interface. We can
        // use that to get both the class and foreign key that will be utilized.
        if (is_null($name))
        {
            list(, $caller, $backtrace) = debug_backtrace(false);

            if ($backtrace['function'] == 'callRelationships')
            {
                // If called using Magniloquent $relationships, we need to go back
                // one extra callback in the backtrace
                $name = snake_case($backtrace['args'][0]);
            }
            else
            {
                $name = snake_case($caller['function']);
            }
        }

        // Next we will guess the type and ID if necessary. The type and IDs may also
        // be passed into the function so that the developers may manually specify
        // them on the relations. Otherwise, we will just make a great estimate.
        list($type, $id) = $this->getMorphs($name, $type, $id);

        $class = $this->$type;

        return $this->belongsTo($class, $id);
    }

    /**
     * Set a given attribute on the model.
     *
     * @param  string $key
     * @param  mixed  $value
     *
     * @return void
     */
    public function setAttribute($key, $value)
    {
        if ($this->valid && $key != $this->getKeyName() && ! in_array($key, $this->getDates()))
            $this->valid = false;

        return parent::setAttribute($key, $value);
    }

    /**
     * Returns the niceNames attribute array and should be overridden by a child class.
     * Legacy support for $this->niceNames is included.
     *
     * @return array
     */
    protected function niceNames()
    {
        return (property_exists($this, 'niceNames') && is_array($this->niceNames)) ? $this->niceNames : array();
    }

    /**
     * Performs validation on the model and return whether it
     * passed or failed
     *
     * @return bool
     */
    public function validate()
    {
        // Merge the rules arrays into one array
        $this->mergeRules();

        // Exclude this object from unique checks if object exists
        if ($this->exists)
        {
            $this->excludeFromUniqueChecks();
        }

        $validation = Validator::make($this->attributes, $this->mergedRules, $this->customMessages);

        // Sets the connection, based on the model's connection variable.
        $validation->getPresenceVerifier()->setConnection($this->connection);

        // Set custom messages on validator
        $validation->setAttributeNames($this->niceNames());

        if ($validation->passes())
        {
            $this->valid = true;

            return true;
        }

        $this->validationErrors = $validation->messages();

        return false;
    }

    /**
     * Returns validationErrors MessageBag
     *
     * @return MessageBag
     */
    public function errors()
    {
        return $this->validationErrors;
    }

    /**
     * Returns if model has been saved to the database
     *
     * @return bool
     */
    public function isSaved()
    {
        return $this->saved;
    }

    /**
     * Returns if the model has passed validation
     *
     * @return bool
     */
    public function isValid()
    {
        return $this->valid;
    }

    /**
     * Will call a relationship method as defined by the $relationships variable
     * on the class.  $relationships is an array of arrays in the following form:
     * array('hasOne', 'model', 'foreignKey')
     * array('hasMany', 'model', 'foreignKey')
     * array('belongsTo', 'model', 'foreignKey')
     * array('belongsToMany', 'model', 'table_name', 'this_id', 'other_id')
     * array('morphTo')
     * array('morphMany', 'model', 'relation_name')
     *
     * @param $method
     *
     * @return mixed
     */
    protected function callRelationships($method)
    {
        $relation_params = static::$relationships[$method];

        $relation_type = array_shift($relation_params);

        return call_user_func_array(array($this, $relation_type), $relation_params);
    }

    /**
     * Merges saving validation rules in with create and update rules
     * to allow rules to differ on create and update.
     *
     * @return array
     */
    protected function mergeRules()
    {
        $rules = static::$rules;
        $output = array();

        if ($this->exists)
            $merged = array_merge_recursive($rules['save'], $rules['update']);
        else
            $merged = array_merge_recursive($rules['save'], $rules['create']);

        foreach ($merged as $field => $rules)
        {
            if (is_array($rules))
                $output[$field] = implode("|", $rules);
            else
                $output[$field] = $rules;
        }

        $this->mergedRules = $output;
    }

    /**
     * Purges unneeded fields by getting rid of all attributes
     * ending in '_confirmation' or starting with '_'
     *
     * @return array
     */
    private function purgeUnneeded()
    {
        $clean = array();
        foreach ($this->attributes as $key => $value)
        {
            if (! Str::endsWith($key, '_confirmation') && ! Str::startsWith($key, '_') && ! in_array($key, static::$purgeable))
                $clean[$key] = $value;
        }
        $this->attributes = $clean;
    }

    /**
     * Auto-hashes the password parameter if it exists
     *
     * @return array
     */
    private function autoHash()
    {
        $attributes = array_merge(static::$needsHash, array('password'));

        foreach ($attributes as $name) {

            if (isset($this->attributes[$name]) && $this->isDirty($name))
            {
                if ( ! Hash::check($this->attributes[$name], $this->getOriginal($name)))
                {
                    $this->attributes[$name] = Hash::make($this->attributes[$name]);
                }
            }
        }
    }

    /**
     *
     */
     private function excludeFromUniqueChecks()
     {
         // iterate over each field
         foreach ($this->mergedRules as $index => $rule)
         {
             // if there is a unique rule in for that field
             if (false !== strpos($rule, 'unique:'))
             {
                 // split rule on pipes
                 $temp_rule = explode('|', $rule);
                 // find key of unique rule
                 $rule_key = '';
                 foreach ($temp_rule as $temp_key => $value)
                 {
                     if (false !== strpos($value, 'unique:'))
                     {
                         $rule_key = $temp_key;
                         break;
                     }
                 }
                 // separate rule params by comma
                 $rule_params = explode(',', $temp_rule[$rule_key]);
                 // Get number of params
                 $count = count($rule_params);
                 if ($count < 3)
                 {
                     switch ($count)
                     {
                        case 1:
                            // add field to array to be added to string
                            $rule_params[] = $index;
                            // allow fall-through to append additional parameters
                        case 2:
                            // add model id number to end to make sure it's ignored
                            $rule_params[] = $this->getKey();
                            // add model primary key field name
                            $rule_params[] = $this->getKeyName();
                            break;
                     }
                     // put everything back together
                     $temp_rule[$rule_key] = implode(',', $rule_params);
                     $this->mergedRules[$index] = $temp_rule;
                 }
             }
         }
     }

}


<?php

/*
 * doctrine-base-repositories (https://github.com/juliangut/doctrine-base-repositories).
 * Doctrine2 utility repositories.
 *
 * @license MIT
 * @link https://github.com/juliangut/doctrine-base-repositories
 * @author Julián Gutiérrez <juliangut@gmail.com>
 */

declare(strict_types=1);

namespace Jgut\Doctrine\Repository;

/**
 * Filters trait.
 */
trait FiltersTrait
{
    /**
     * List of disabled filters.
     *
     * @var object[]
     */
    protected $disabledFilters = [];

    /**
     * Disable all filters.
     */
    public function disableFilters()
    {
        foreach (\array_keys($this->getFilterCollection()->getEnabledFilters()) as $filter) {
            $this->disableFilter($filter);
        }
    }

    /**
     * Disable filter.
     *
     * @param string $filter
     */
    public function disableFilter(string $filter)
    {
        if (\in_array($filter, $this->disabledFilters, true)) {
            return;
        }

        $this->getFilterCollection()->disable($filter);

        $this->disabledFilters[] = $filter;
    }

    /**
     * Restore all disabled filters.
     */
    public function restoreFilters()
    {
        $filterCollection = $this->getFilterCollection();

        foreach ($this->disabledFilters as $filter) {
            $filterCollection->enable($filter);
        }

        $this->disabledFilters = [];
    }

    /**
     * Restore disabled filter.
     *
     * @param string $filter
     */
    public function restoreFilter(string $filter)
    {
        $position = \array_search($filter, $this->disabledFilters, true);
        if ($position === false) {
            return;
        }

        $this->getFilterCollection()->enable($filter);

        \array_splice($this->disabledFilters, $position, 1);
    }

    /**
     * Get filter collection.
     *
     * @return object
     */
    abstract protected function getFilterCollection();

    /**
     * Get object manager.
     *
     * @return \Doctrine\Common\Persistence\ObjectManager
     */
    abstract protected function getManager();
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.2
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Http\Datatables;

use Antares\Datatables\Services\DataTable;
use Antares\Support\Facades\Foundation;

class Roles extends DataTable
{

    /**
     * items per page
     *
     * @var mixed
     */
    public $perPage = 25;

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return Foundation::make('antares.role')->managers()->select(['id', 'full_name', 'description']);
    }

    /**
     * {@inheritdoc}
     */
    public function ajax()
    {
        $roleId        = user()->roles->first()->id;
        $acl           = app('antares.acl')->make('antares/acl');
        $canEditRole   = $acl->can('edit-role');
        $canDeleteRole = $acl->can('delete-role');

        return $this->prepare()
                        ->addColumn('action', $this->getActionsColumn($roleId, $canEditRole, $canDeleteRole))
                        ->editColumn('description', function ($model) {
                            return (strlen($model->description) > 0) ? value($model->description) : '---';
                        })
                        ->make(true);
    }

    /**
     * {@inheritdoc}
     */
    public function html()
    {
        return $this->setName('Roles List')
                        ->addColumn(['data' => 'id', 'name' => 'id', 'title' => 'Id'])
                        ->addColumn(['data' => 'full_name', 'name' => 'full_name', 'title' => 'Group name', 'className' => 'bolded'])
                        ->addColumn(['data' => 'description', 'name' => 'description', 'title' => 'Description'])
                        ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false])
                        ->setDeferedData();
    }

    /**
     * Get actions column for table builder.
     *
     * @return callable
     */

    /**
     * prepare datatable row actions
     *
     * @param mixed $roleId
     * @param boolean $canEditRole
     * @param boolean $canDeleteRole
     * @return callable
     */
    protected function getActionsColumn($roleId, $canEditRole, $canDeleteRole)
    {

        return function ($row) use($roleId, $canEditRole, $canDeleteRole) {

            $btns = [];
            $html = app('html');
            if ($canEditRole) {
                array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/edit"), trans('antares/acl::title.edit_details'), ['data-icon' => 'edit'])));
                array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/acl"), trans('antares/acl::title.acl_rules'), ['data-icon' => 'accounts-alt'])));
            }
            if ($row->id !== $roleId and $canDeleteRole) {

                $url = handles("antares::acl/index/roles/{$row->id}/delete", ['csrf' => true]);

                $class           = 'triggerable confirm';
                $dataTitle       = trans('Are you sure?');
                $dataDescription = trans('antares/acl::global.deleteing_role', ['name' => $row->name]);

                if ($row->users->count()) {
                    publish('acl', ['js/delete-group-denied.js']);
                    $url             = '#';
                    $class           = 'bindable delete-group-denied';
                    $dataTitle       = trans('This action is not allowed');
                    $dataDescription = trans('There are users attached to this group. Only empty groups can be removed.');
                }

                array_push($btns, $html->create('li', $html->link($url, trans('Delete'), [
                                    'class'            => $class,
                                    'data-icon'        => 'delete',
                                    'data-title'       => $dataTitle,
                                    'data-description' => $dataDescription
                ])));
            }
            if (empty($btns)) {
                return '';
            }
            $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get();
            return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get();
        };
    }

}


<?php

namespace Mamikon\RoleManager\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User;
/**
 * Role model
 *
 * @category Laravel_Package
 * @package  Mamikon\RoleManager
 * @author   Mamikon Arakelyan <m.araqelyan@gmail.com>
 * @license  https://github.com/mamikon/role-manager/blob/master/LICENSE.md MIT
 * @link     https://github.com/mamikon/role-manager
 */
class Roles extends Model
{
    protected $fillable = ['name', 'description'];

    /**
     * Roles constructor.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->table = config('roleManager.rolesTable');
    }

    /**
     * Permission Relation
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function permissions()
    {
        return $this->belongsToMany(Permissions::class);
    }

    /**
     * Users relation
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Check if user has role
     *
     * @param User $user
     *
     * @return bool
     */
    public function belongsToUser(User $user)
    {
        return !!$this->users()->where('user_id', $user->id)->count();
    }

    /**
     * Assign Role to User
     *
     * @param User $user
     *
     * @return bool
     */
    public function assignToUser(User $user)
    {
        if ($this->belongsToUser($user)) {
            return true;
        }
        $this->users()->attach($user->id);
        return true;
    }
}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle;

use PHPMentors\PageflowerBundle\DependencyInjection\Compiler\GeneratePageflowDefinitionsPass;
use PHPMentors\PageflowerBundle\DependencyInjection\Compiler\ReplaceAppVariableDefinitionPass;
use PHPMentors\PageflowerBundle\DependencyInjection\Compiler\ReplaceSessionDefinitionPass;
use PHPMentors\PageflowerBundle\DependencyInjection\Compiler\ReplaceTemplatingGlobalsDefinitionPass;
use PHPMentors\PageflowerBundle\DependencyInjection\PHPMentorsPageflowerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class PHPMentorsPageflowerBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new GeneratePageflowDefinitionsPass());
        $container->addCompilerPass(new ReplaceSessionDefinitionPass());
        $container->addCompilerPass(new ReplaceTemplatingGlobalsDefinitionPass());
        $container->addCompilerPass(new ReplaceAppVariableDefinitionPass());
    }

    /**
     * {@inheritdoc}
     */
    public function getContainerExtension()
    {
        if ($this->extension === null) {
            $this->extension = new PHPMentorsPageflowerExtension();
        }

        return $this->extension;
    }
}


<?php namespace Kayex;

class HttpCodes
{
    // [Informational 1xx]
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;

    // [Successful 2xx]
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NONAUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;

    // [Redirection 3xx]
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_UNUSED= 306;
    const HTTP_TEMPORARY_REDIRECT = 307;

    // [Client Error 4xx]
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED  = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;

    // [Server Error 5xx]
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

    /**
     * Checks whether a status code can be considered successful.
     *
     * @param $code
     * @return bool
     */
    public static function isSuccessful($code)
    {
        switch($code) {
            case self::HTTP_OK:
            case self::HTTP_CREATED:
            case self::HTTP_ACCEPTED:
            case self::HTTP_NONAUTHORITATIVE_INFORMATION:
            case self::HTTP_NO_CONTENT:
            case self::HTTP_RESET_CONTENT:
            case self::HTTP_PARTIAL_CONTENT:
                return true;
            default:
                return false;
        }
    }
}


<?php

namespace Adback\ApiClient\Query;

use Adback\ApiClient\Client\Client;
use Adback\ApiClient\Driver\ScriptCacheInterface;

/**
 * Class ScriptUrlQuery
 */
class ScriptUrlQuery implements QueryInterface
{
    protected $cache;
    protected $token;
    protected $apiUrl;
    protected $client;
    protected $scriptUrl;

    /**
     * @param Client               $client
     * @param ScriptCacheInterface $cache
     * @param string               $token
     * @param string               $apiUrl
     * @param string               $scriptUrl
     */
    public function __construct(Client $client, ScriptCacheInterface $cache, $token, $apiUrl = 'https://www.adback.co/api', $scriptUrl = 'script/me')
    {
        $this->cache = $cache;
        $this->token = $token;
        $this->apiUrl = $apiUrl;
        $this->client = $client;
        $this->scriptUrl = $scriptUrl;
    }

    /**
     * Get the script info and store them
     */
    public function execute()
    {
        $url = sprintf('%s/%s?_format=json&access_token=%s',
            $this->apiUrl,
            $this->scriptUrl,
            $this->token
        );

        $response = $this->client->get($url);

        if (200 !== $response->getStatusCode()) {
            return;
        }

        $scriptUrlFacade = json_decode($response->getBody(), true);

        if (array_key_exists('analytics_domain', $scriptUrlFacade) && null != $scriptUrlFacade['analytics_domain']) {
            $this->cache->setAnalyticsUrl($scriptUrlFacade['analytics_domain']);
            $this->cache->setAnalyticsScript($scriptUrlFacade['analytics_script']);
        } else {
            $this->cache->clearAnalyticsData();
        }

        if (array_key_exists('message_script', $scriptUrlFacade) && null != $scriptUrlFacade['message_script']) {
            $this->cache->setMessageUrl($scriptUrlFacade['message_domain']);
            $this->cache->setMessageScript($scriptUrlFacade['message_script']);
        } else {
            $this->cache->clearMessageData();
        }

        if (array_key_exists('autopromo_banner_script', $scriptUrlFacade) && null != $scriptUrlFacade['autopromo_banner_script']) {
            $this->cache->setAutopromoBannerUrl($scriptUrlFacade['autopromo_banner_domain']);
            $this->cache->setAutopromoBannerScript($scriptUrlFacade['autopromo_banner_script']);
        } else {
            $this->cache->clearAutopromoBannerData();
        }

        if (array_key_exists('iab_banner_script', $scriptUrlFacade) && null != $scriptUrlFacade['iab_banner_script']) {
            $this->cache->setIabBannerUrl($scriptUrlFacade['iab_banner_domain']);
            $this->cache->setIabBannerScript($scriptUrlFacade['iab_banner_script']);
        } else {
            $this->cache->clearIabBannerData();
        }

        if (array_key_exists('product_script', $scriptUrlFacade) && null != $scriptUrlFacade['product_script']) {
            $this->cache->setProductUrl($scriptUrlFacade['product_domain']);
            $this->cache->setProductScript($scriptUrlFacade['product_script']);
        } else {
            $this->cache->clearProductData();
        }
    }
}


<?php
/**
 * Copyright © OXID eSales AG. All rights reserved.
 * See LICENSE file for license details.
 */

namespace OxidEsales\EcondaTrackingComponent\Adapter\Modifiers;

use OxidEsales\EcondaTrackingComponent\Adapter\Helper\CategoryPathBuilder;
use OxidEsales\EcondaTrackingComponent\Adapter\ProductPreparation\ProductDataPreparator;
use OxidEsales\EcondaTrackingComponent\TrackingCodeGenerator\ActivePageEntityInterface;
use /** @noinspection PhpUndefinedClassInspection */
    OxidEsales\Eshop\Application\Model\Article;
use OxidEsales\Eshop\Core\Registry;

/**
 * Class responsible for adding data to entity.
 */
class EntityModifierByCurrentBasketAction
{
    /**
     * @var CategoryPathBuilder
     */
    private $categoryPathBuilder;

    /**
     * @var ProductDataPreparator
     */
    private $productDataPreparator;

    /**
     * @var ActivePageEntityInterface
     */
    private $pageEntity;

    /**
     * @param CategoryPathBuilder   $categoryPathBuilder
     * @param ProductDataPreparator $productDataPreparator
     */
    public function __construct($categoryPathBuilder, $productDataPreparator)
    {
        $this->categoryPathBuilder = $categoryPathBuilder;
        $this->productDataPreparator = $productDataPreparator;
    }

    /**
     * @param ActivePageEntityInterface $activePageEntity
     *
     * @return ActivePageEntityInterface
     */
    public function modifyEntity($activePageEntity)
    {
        $this->pageEntity = $activePageEntity;
        // get the last Call for special handling function "tobasket", "changebasket"
        if (($lastCall = Registry::getSession()->getVariable('aLastcall'))) {
            Registry::getSession()->deleteVariable('aLastcall');
        }

        // ADD To Basket and Remove from Basket
        if (is_array($lastCall) && count($lastCall)) {
            $callAction = key($lastCall);
            $callData = current($lastCall);

            switch ($callAction) {
                case 'changebasket':
                    $this->changeBasketAction($callData);
                    break;
                case 'tobasket':
                    $this->toBasketAction($callData);
                    break;
            }
        }

        return $this->pageEntity;
    }

    /**
     * @param array $callData
     */
    private function changeBasketAction($callData)
    {
        foreach ($callData as $itemId => $itemData) {
            $product = oxNew(Article::class);
            if ($product->load($itemData['aid'])) {
                if ($itemData['oldam'] > $itemData['am'] && $product->load($itemData['aid'])) {
                    //ECONDA FIX always use the main category
                    //$sPath = $this->_getDeepestCategoryPath( $product );
//                            $sPath = $this->_getBasketProductCatPath($product);
//                            $oEmos->removeFromBasket($this->_convProd2EmosItem($product, $sPath, ($itemData['oldam'] - $itemData['am'])));
//                            //$oEmos->appendPreScript($itemData['oldam'].'->'.$itemData['am'].':'.$product->load( $itemData['aid']));
                } elseif ($itemData['oldam'] < $itemData['am'] && $product->load($itemData['aid'])) {
                    $sPath = $this->categoryPathBuilder->getBasketProductCategoryPath($product);
                    $this->pageEntity->setProductToBasket($this->productDataPreparator->prepareForTransaction($product, $sPath, $itemData['am'] - $itemData['oldam']));
                }
            }
        }
    }

    /**
     * @param array $callData
     */
    private function toBasketAction($callData)
    {
        foreach ($callData as $itemId => $itemData) {
            // ECONDA FIX if there is a "add to basket" in the artcle list view, we do not have a product ID here
            $product = oxNew(Article::class);
            if ($product->load($itemId)) {
                $path = $this->categoryPathBuilder->getBasketProductCategoryPath($product);
                $this->pageEntity->setProductToBasket($this->productDataPreparator->prepareForTransaction($product, $path, $itemData['am']));
            }
        }
    }
}


<?php
/**
 * Copyright © OXID eSales AG. All rights reserved.
 * See LICENSE file for license details.
 */

namespace OxidEsales\EcondaTrackingComponent\Adapter\Page;

use OxidEsales\Eshop\Core\Registry;

/**
 * Class responsible for returning identifiers from request.
 */
class PageIdentifiers
{
    /**
     * Returns purpose of this page (current view name).
     *
     * @return string
     */
    public function getCurrentControllerName()
    {
        $activeController = Registry::getConfig()->getActiveView();
        $className = $activeController->getClassKey();

        return $className ? strtolower($className) : 'start';
    }

    /**
     * Returns name of current action function.
     *
     * @return string
     */
    public function getCurrentFunctionName()
    {
        $currentView = Registry::getConfig()->getActiveView();
        $functionName = $currentView->getFncName();

        return $functionName;
    }

    /**
     * Returns current controller template name.
     *
     * @return string
     */
    public function getCurrentTemplateName()
    {
        if (!($currentTemplate = basename((string) Registry::getRequest()->getRequestEscapedParameter('tpl')))) {
            // in case template was not defined in request
            $currentTemplate = Registry::getConfig()->getActiveView()->getTemplateName();
        }

        return $currentTemplate;
    }

    /**
     * @return string
     */
    public function getPageId()
    {
        $sPageId = Registry::getConfig()->getShopId() .
            $this->getCurrentControllerName() .
            $this->getCurrentTemplateName() .
            Registry::getRequest()->getRequestEscapedParameter('cnid') .
            Registry::getRequest()->getRequestEscapedParameter('anid') .
            Registry::getRequest()->getRequestEscapedParameter('option');

        return md5($sPageId);
    }
}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('phpmentors_pageflower')
            ->children()
                ->arrayNode('conversation')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('request_parameter_name')
                            ->defaultValue('CONVERSATION_ID')
                            ->cannotBeEmpty()
                        ->end()
                        ->scalarNode('session_storage_name')
                            ->defaultValue('_pageflower_conversations')
                            ->cannotBeEmpty()
                        ->end()
                        ->booleanNode('end_on_next_step_of_end_page')
                            ->defaultFalse()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


<?php
/*
 * This file is part of the prooph/ProophEventStoreModule.
 * (c) Alexander Miertsch <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 03.09.14 - 21:53
 */

namespace ProophEventStoreModule\Factory;

use Prooph\EventStore\Stream\SingleStreamStrategy;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class SingleStreamStrategyFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $singleStreamName = null;

        if ($serviceLocator->has('configuration')) {
            $config = $serviceLocator->get('configuration');

            if (isset($config['prooph.event_store']) && isset($config['prooph.event_store']['single_stream_name'])) {
                $singleStreamName = $config['prooph.event_store']['single_stream_name'];
            }
        }

        return new SingleStreamStrategy($serviceLocator->get('prooph.event_store'), $singleStreamName);
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Http\Presenters;

use Antares\Acl\Http\Datatables\Roles as Datatables;
use Antares\Acl\Http\Form\Role as RoleForm;
use Antares\Acl\Http\Breadcrumb\Breadcrumb;
use Antares\Acl\Contracts\ModulesAdapter;
use Antares\Model\Role as Eloquent;
use Illuminate\Container\Container;

class Role extends Presenter
{

    /**
     * application container
     *
     * @var Container
     */
    protected $container;

    /**
     * modules adapter instance
     *
     * @var ModulesAdapter
     */
    protected $adapter;

    /**
     * breadcrumbs instance
     *
     * @var Breadcrumb
     */
    protected $breadcrumb;

    /**
     * datatables instance
     *
     * @var Datatables
     */
    protected $datatables;

    /**
     * Create a new Role presenter.
     *
     * @param Container $container
     * @param ModulesAdapter $adapter
     * @param Breadcrumb $breadcrumb
     */
    public function __construct(Container $container, ModulesAdapter $adapter, Breadcrumb $breadcrumb, Datatables $datatables)
    {
        $this->container  = $container;
        $this->adapter    = $adapter;
        $this->breadcrumb = $breadcrumb;
        $this->datatables = $datatables;
    }

    /**
     * response for roles list
     *
     * @return \Illuminate\View\View
     */
    public function table()
    {
        $this->breadcrumb->onInit();
        return $this->datatables->render('antares/acl::roles.index');
    }

    /**
     * View form generator for Antares\Model\Role.
     *
     * @param  \Antares\Model\Role  $model
     *
     * @return \Antares\Contracts\Html\Form\Builder
     */
    public function form(Eloquent $model = null)
    {
        $this->breadcrumb->onRoleCreateOREdit($model);
        return new RoleForm($model);
    }

    /**
     * edit action presenter
     *
     * @return type
     */
    public function edit(Eloquent $eloquent, array $available = array())
    {
        publish('acl', ['js/control.js']);
        $id         = $eloquent->id;
        $instances  = $this->container->make('antares.acl')->all();
        $form       = $this->form($eloquent);
        $modules    = $this->adapter->modules();
        $collection = $this->container->make('antares.memory')->make('collector')->all();
        foreach ($collection as $item) {
            array_push($available, $item['aid']);
        }
        return compact('eloquent', 'form', 'modules', 'instances', 'available', 'id');
    }

    public function acl(Eloquent $eloquent)
    {
        $this->breadcrumb->onAcl($eloquent);
        app('antares.asset')->container('antares/foundation::application')->add('webpack_forms_advanced', '/webpack/forms_advanced.js', ['app_cache'])->add('webpack_acl', '/webpack/view_acl.js', ['webpack_forms_advanced']);
        $id     = $eloquent->id;
        $groups = Eloquent::query()->newQuery()->get()->all();

        return view('antares/acl::roles.acl', compact('groups', 'id'));
    }

}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Processor;

use Antares\Acl\Contracts\Listener\Account\UserCreator as UserCreatorListener;
use Antares\Acl\Contracts\Listener\Account\UserRemover as UserRemoverListener;
use Antares\Acl\Contracts\Listener\Account\UserUpdater as UserUpdaterListener;
use Antares\Acl\Http\Presenters\User as Presenter;
use Antares\Users\Validation\User as Validator;
use Antares\Support\Facades\Foundation;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Antares\Model\User as Eloquent;
use Illuminate\Support\Facades\DB;
use Exception;

class User extends Processor
{

    /**
     * Create a new processor instance.
     *
     * @param  \Antares\Users\Http\Presenters\User  $presenter
     * @param  \Antares\Users\Validation\User  $validator
     */
    public function __construct(Presenter $presenter, Validator $validator)
    {
        $this->presenter = $presenter;
        $this->validator = $validator;
    }

    /**
     * View list users page.
     *
     * @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
     */
    public function index()
    {
        return $this->presenter->table();
    }

    /**
     * View create user page.
     *
     * @param  \Antares\Contracts\Foundation\Listener\Account\UserCreator  $listener
     *
     * @return mixed
     */
    public function create(UserCreatorListener $listener)
    {
        $eloquent = Foundation::make('antares.user');
        $form     = $this->presenter->form($eloquent, 'create');
        $this->fireEvent('form', [$eloquent, $form]);
        return $listener->showUserCreator(compact('eloquent', 'form'));
    }

    /**
     * View edit user page.
     *
     * @param  \Antares\Contracts\Foundation\Listener\Account\UserUpdater  $listener
     * @param  string|int  $id
     *
     * @return mixed
     */
    public function edit(UserUpdaterListener $listener, $id)
    {
        $eloquent = Foundation::make('antares.user');
        if ($id !== auth()->user()->id) {
            $eloquent = $eloquent->where('id', $id)->withoutGlobalScopes()->whereHas('roles', function ($query) {
                        $role    = user()->roles->first();
                        $roles   = $role->getChilds();
                        $roles[] = $role->id;
                        $query->whereIn('role_id', array_values($roles));
                    })->first();
            if (is_null($eloquent)) {
                return $listener->noAccessToEdit();
            }
        } else {
            $eloquent = $eloquent->findOrFail($id);
        }

        $form = $this->presenter->form($eloquent, 'update');
        $this->fireEvent('form', [$eloquent, $form]);

        return $listener->showUserChanger(compact('eloquent', 'form'));
    }

    /**
     * Store a user.
     *
     * @param  \Antares\Contracts\Foundation\Listener\Account\UserCreator  $listener
     * @param  array   $input
     *
     * @return mixed
     */
    public function store(UserCreatorListener $listener, array $input)
    {

        $user           = Foundation::make('antares.user');
        $user->status   = Eloquent::UNVERIFIED;
        $user->password = $input['password'];

        $form = $this->presenter->form($user);
        if (!$form->isValid()) {
            return $listener->createUserFailedValidation($form->getMessageBag());
        }

        try {
            $this->saving($user, $input, 'create');
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->createUserFailed(['error' => $e->getMessage()]);
        }

        return $listener->userCreated();
    }

    /**
     * Update a user.
     *
     * @param  \Antares\Contracts\Foundation\Listener\Account\UserUpdater  $listener
     * @param  string|int  $id
     * @param  array  $input
     *
     * @return mixed
     */
    public function update(UserUpdaterListener $listener, $id, array $input)
    {
        if ((string) $id !== $input['id']) {
            return $listener->abortWhenUserMismatched();
        }
        $user           = Foundation::make('antares.user')->withoutGlobalScopes()->findOrFail($id);
        !empty($input['password']) && $user->password = $input['password'];
        try {
            $this->saving($user, $input, 'update');
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->updateUserFailed(['error' => $e->getMessage()]);
        }

        return $listener->userUpdated();
    }

    /**
     * Destroy a user.
     *
     * @param  \Antares\Contracts\Foundation\Listener\Account\UserRemover  $listener
     * @param  string|int  $id
     *
     * @return mixed
     */
    public function destroy(UserRemoverListener $listener, $id)
    {
        if (user()->id == $id) {
            return $listener->userDeletionFailed(['error' => trans('antares/acl::messages.unable_to_delete_self')]);
        }
        $user = Foundation::make('antares.user');
        if (app('antares.acl')->make('antares/acl')->can('login-as-user')) {
            $user = $user->withoutGlobalScopes();
        }

        $user = $user->findOrFail($id);
        if ((string) $user->id === (string) Auth::user()->id) {
            return $listener->selfDeletionFailed();
        }

        try {
            $this->fireEvent('deleting', [$user]);

            DB::transaction(function () use ($user) {
                $user->delete();
            });

            $this->fireEvent('deleted', [$user]);
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->userDeletionFailed(['error' => $e->getMessage()]);
        }

        return $listener->userDeleted();
    }

    /**
     * Save the user.
     *
     * @param  \Antares\Model\User  $user
     * @param  array  $input
     * @param  string  $type
     *
     * @return bool
     */
    protected function saving(Eloquent $user, $input = [], $type = 'create')
    {
        $beforeEvent = ($type === 'create' ? 'creating' : 'updating');
        $afterEvent  = ($type === 'create' ? 'created' : 'updated');

        $user->firstname = $input['firstname'];
        $user->lastname  = $input['lastname'];
        $user->email     = $input['email'];

        if (isset($input['status'])) {
            $user->status = $input['status'];
        }
        if ($user->exists && !isset($input['status'])) {
            $user->status = 0;
        }

        $this->fireEvent($beforeEvent, [$user]);
        $this->fireEvent('saving', [$user]);

        DB::transaction(function () use ($user, $input) {
            $user->save();
            $user->roles()->sync($input['roles']);
        });

        $this->fireEvent($afterEvent, [$user]);
        $this->fireEvent('saved', [$user]);

        return true;
    }

    /**
     * Fire Event related to eloquent process.
     *
     * @param  string  $type
     * @param  array   $parameters
     *
     * @return void
     */
    protected function fireEvent($type, array $parameters = [])
    {
        Event::fire("antares.{$type}: users", $parameters);
        Event::fire("antares.{$type}: user.account", $parameters);
    }

    /**
     * Gets patterned url for search engines
     *
     * @return String
     */
    public static function getPatternUrl()
    {
        return handles('antares::users/{id}/edit');
    }

}


<?php

namespace UFCOE\Elgg;

class SitePath {

	/**
	 * The $path exploded by /. E.g. http://example.com/elgg/foo/bar => ["foo", "bar"]
	 *
	 * @return string[]
	 */
	protected $url_segments = [];

	/**
	 * The entity's GUID, if the URL likely represent an entity on the Elgg site, else 0
	 *
	 * @var int
	 */
	protected $guid = 0;

	/**
	 * The entity's GUID, if the URL likely represent a container entity on the Elgg site, else 0
	 *
	 * @var int
	 */
	protected $container_guid = 0;

	/**
	 * The action name, if the URL likely represents an Elgg action, else ''
	 *
	 * @var string
	 */
	protected $action = '';

	/**
	 * The username, if the URL likely represents an Elgg user, else ''
	 *
	 * @var string
	 */
	protected $username = '';

	/**
	 * Constructor
	 *
	 * @param string $path Path within Elgg site. E.g. "blog/view/123/blog-title"
	 */
	public function __construct($path) {
		$path = SiteUrl::normalizePath($path);

		if ($path === '') {
			return;
		}

		$this->url_segments = explode('/', $path);
		$identifier = $this->url_segments[0];
		$handler_segments = array_slice($this->url_segments, 1);

		if ($identifier === 'action' && $handler_segments) {
			$this->action = implode('/', $handler_segments);
			return;
		}

		if ($identifier === 'profile' && $handler_segments) {
			$this->username = urldecode($handler_segments[0]);
			return;
		}

		if ((count($this->url_segments) >= 3)
			&& in_array($this->url_segments[1], array('view', 'read'))
			&& preg_match('~^[1-9]\\d*$~', $this->url_segments[2])
		) {
			$this->guid = (int)$this->url_segments[2];

		} elseif (preg_match('~^[^/]+/group/([1-9]\\d*)/all$~', $this->getPath(), $m)) {
			// this is a listing of group items
			$this->container_guid = (int) $m[1];

		} elseif (preg_match('~^[^/]+/add/([1-9]\\d*)$~', $this->getPath(), $m)) {
			// this is a new item creation page
			$this->container_guid = (int) $m[1];

		} elseif (preg_match('~^(?:[^/]+/)+([1-9]\\d*)(?:$|/)~', $this->getPath(), $m)) {
			// less-reliable guessing (e.g. groups/profile/123)
			$this->guid = (int) $m[1];
		}
	}

	/**
	 * Path within the Elgg site, with no trailing/leading slashes. Empty string is home page.
	 * E.g. http://example.com/elgg/foo/bar => "foo/bar"
	 *
	 * @return string
	 */
	public function getPath() {
		return implode('/', $this->url_segments);
	}

	/**
	 * The path split by "/". E.g. http://example.com/elgg/foo/bar => ["foo", "bar"]
	 *
	 * @return string[]
	 */
	public function getUrlSegments() {
		return $this->url_segments;
	}

	/**
	 * The entity's GUID, if the URL likely represents an entity, else 0
	 *
	 * @return int
	 */
	public function getGuid() {
		return $this->guid;
	}

	/**
	 * The entity's GUID, if the URL likely represents a container entity, else 0
	 *
	 * @return int
	 */
	public function getContainerGuid() {
		return $this->container_guid;
	}

	/**
	 * The action name, if the URL likely represents an Elgg action, else ''
	 *
	 * @return string
	 */
	public function getAction() {
		return $this->action;
	}

	/**
	 * The username, if the URL likely represents an Elgg user, else ''
	 *
	 * @return string
	 */
	public function getUsername() {
		return $this->username;
	}

	/**
	 * Is this path within the given path?
	 *
	 * E.g. if the current path is "blog/view/123", this would return true for "blog",
	 * but false for "bl" or "blog/vi".
	 *
	 * @param string $path Path to compare. E.g. "blog/view"
	 *
	 * @return bool
	 */
	public function isWithinPath($path) {
		$path = SiteUrl::normalizePath($path);

		$current_path = $this->getPath() . '/';
		$path = trim($path, '/') . '/';

		if ($path === '/') {
			return true;
		}

		return (0 === strpos($current_path, $path));
	}
}


<?php

/*
 * This file is part of the Active Collab DatabaseObject project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseObject\Collection;

use ActiveCollab\DatabaseConnection\Result\ResultInterface;
use ActiveCollab\DatabaseObject\Collection;
use ActiveCollab\DatabaseObject\Entity\EntityInterface;
use Doctrine\Common\Inflector\Inflector;
use InvalidArgumentException;
use LogicException;

/**
 * @package ActiveCollab\DatabaseObject\Collection
 */
abstract class Type extends Collection
{
    /**
     * @var string
     */
    private $registered_type;

    /**
     * Return type that this collection works with.
     *
     * @return string
     */
    abstract public function getType();

    /**
     * Return registered type.
     *
     * @return string
     */
    protected function getRegisteredType()
    {
        if (empty($this->registered_type)) {
            $this->registered_type = $this->pool->getRegisteredType($this->getType());

            if (empty($this->registered_type)) {
                throw new InvalidArgumentException("Type '" . $this->getType() . "' is not registered");
            }
        }

        return $this->registered_type;
    }

    // ---------------------------------------------------
    //  Etag
    // ---------------------------------------------------

    /**
     * Return true if this object can be tagged and cached on client side.
     *
     * @return bool|null
     */
    public function canBeEtagged()
    {
        return (bool) $this->getTimestampField();
    }

    /**
     * Cached tag value.
     *
     * @var string
     */
    private $tag = false;

    /**
     * Return collection etag.
     *
     * @param  string $visitor_identifier
     * @param  bool   $use_cache
     * @return string
     */
    public function getEtag($visitor_identifier, $use_cache = true)
    {
        $timestamp_field = $this->getTimestampField();

        if ($timestamp_field && ($this->tag === false || !$use_cache)) {
            $this->tag = $this->prepareTagFromBits($this->getAdditionalIdentifier(), $visitor_identifier, $this->getTimestampHash($timestamp_field));
        }

        return $this->tag;
    }

    /**
     * @return string
     */
    protected function getAdditionalIdentifier()
    {
        return 'na';
    }

    /**
     * Cached time stamp field name.
     *
     * @var string|bool
     */
    private $timestamp_field = null;

    /**
     * Return timestamp field name.
     *
     * @return string|bool
     */
    public function getTimestampField()
    {
        if ($this->timestamp_field === null) {
            $fields = $this->pool->getTypeFields($this->getRegisteredType());

            if (in_array('updated_at', $fields)) {
                $this->timestamp_field = 'updated_at';
            } elseif (in_array('created_at', $fields)) {
                $this->timestamp_field = 'created_at';
            } else {
                $this->timestamp_field = false;
            }
        }

        return $this->timestamp_field;
    }

    /**
     * Return timestamp hash.
     *
     * @param  string $timestamp_field
     * @return string
     */
    public function getTimestampHash($timestamp_field)
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        $table_name = $this->getTableName();
        $conditions = $this->getConditions() ? " WHERE {$this->getConditions()}" : '';

        if ($this->count() > 0) {
            if ($join_expression = $this->getJoinExpression()) {
                return sha1($this->connection->executeFirstCell("SELECT GROUP_CONCAT($table_name.$timestamp_field ORDER BY $table_name.id SEPARATOR ',') AS 'timestamp_hash' FROM $table_name $join_expression $conditions"));
            } else {
                return sha1($this->connection->executeFirstCell("SELECT GROUP_CONCAT($table_name.$timestamp_field ORDER BY id SEPARATOR ',') AS 'timestamp_hash' FROM $table_name $conditions"));
            }
        }

        return sha1(get_class($this));
    }

    // ---------------------------------------------------
    //  Model interaction
    // ---------------------------------------------------

    /**
     * Run the query and return DB result.
     *
     * @return ResultInterface|EntityInterface[]
     */
    public function execute()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        if (is_callable($this->pre_execute_callback)) {
            $ids = $this->executeIds();

            if ($ids_count = count($ids)) {
                call_user_func($this->pre_execute_callback, $ids);

                if ($ids_count > 1000) {
                    $sql = $this->getSelectSql(); // Don't escape more than 1000 ID-s using DB::escape(), let MySQL do the dirty work instead of PHP
                } else {
                    $escaped_ids = $this->connection->escapeValue($ids);

                    $sql = "SELECT * FROM {$this->getTableName()} WHERE id IN ($escaped_ids) ORDER BY FIELD (id, $escaped_ids)";
                }

                return $this->pool->findBySql($this->getType(), $sql);
            }

            return null;
        } else {
            return $this->pool->findBySql($this->getType(), $this->getSelectSql());
        }
    }

    /**
     * @var int[]
     */
    private $ids = false;

    /**
     * Return ID-s of matching records.
     *
     * @return array
     */
    public function executeIds()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        if ($this->ids === false) {
            $this->ids = $this->connection->executeFirstColumn($this->getSelectSql(false));

            if (empty($this->ids)) {
                $this->ids = [];
            }
        }

        return $this->ids;
    }

    /**
     * Return number of items that will be displayed on the current page of paginated collection (or total, if collection is not paginated).
     *
     * @return int
     */
    public function countIds()
    {
        return count($this->executeIds());
    }

    /**
     * @param  bool   $all_fields
     * @return string
     */
    private function getSelectSql($all_fields = true)
    {
        $offset = $this->getCurrentPage() !== null ? ($this->getCurrentPage() - 1) * $this->getItemsPerPage() : null;
        $limit = $this->getItemsPerPage();

        $fields = $all_fields ? '*' : '`id`';
        $table_name = $this->connection->escapeTableName($this->getTableName());
        $conditions = $this->getConditions() ? "WHERE {$this->getConditions()}" : '';

        if ($order_by = $this->getOrderBy()) {
            $order_by = "ORDER BY $this->order_by";
        } else {
            $order_by = '';
        }

        $limit = is_int($offset) && $limit ? "LIMIT $offset, $limit" : '';

        if ($join_expression = $this->getJoinExpression()) {
            return "SELECT $table_name.$fields FROM $table_name $join_expression $conditions $order_by $limit";
        } else {
            return "SELECT $fields FROM $table_name $conditions $order_by $limit";
        }
    }

    /**
     * Return number of records that match conditions set by the collection.
     *
     * @return int
     */
    public function count()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        $table_name = $this->connection->escapeTableName($this->getTableName());
        $conditions = $this->getConditions() ? " WHERE {$this->getConditions()}" : '';

        if ($join_expression = $this->getJoinExpression()) {
            return (int) $this->connection->executeFirstCell("SELECT COUNT($table_name.`id`) FROM $table_name $join_expression $conditions");
        } else {
            return $this->connection->executeFirstCell("SELECT COUNT(`id`) AS 'row_count' FROM $table_name $conditions");
        }
    }

    /**
     * Return model table name.
     *
     * @var string
     */
    private $table_name;

    /**
     * Return model table name.
     *
     * @return mixed
     */
    public function getTableName()
    {
        if (empty($this->table_name)) {
            $this->table_name = $this->pool->getTypeTable($this->getRegisteredType());
        }

        return $this->table_name;
    }

    /**
     * Cached order by value.
     *
     * @var string|null
     */
    private $order_by = false;

    /**
     * Return order by.
     *
     * @return string|null
     */
    public function getOrderBy()
    {
        if ($this->order_by === false) {
            $this->order_by = $this->pool->getEscapedTypeOrderBy($this->getRegisteredType());
        }

        return $this->order_by;
    }

    /**
     * Set how system should order records in this collection.
     *
     * @param  string $value
     * @return $this
     */
    public function &orderBy($value)
    {
        if ($value === null || $value) {
            $this->order_by = $value;
        } else {
            throw new InvalidArgumentException('$value can be NULL or a valid order by value');
        }

        return $this;
    }

    /**
     * Collection conditions.
     *
     * @var string
     */
    private $conditions = [];

    /**
     * Cached conditions as string.
     *
     * Call to where() resets this value to false, and getConditions() rebuilds it if it FALSE on request.
     *
     * @var string|bool
     */
    private $conditions_as_string = false;

    /**
     * Return conditions.
     *
     * @return string|null
     */
    public function getConditions()
    {
        if ($this->conditions_as_string === false) {
            switch (count($this->conditions)) {
                case 0:
                    $this->conditions_as_string = '';
                    break;
                case 1:
                    $this->conditions_as_string = $this->conditions[0];
                    break;
                default:
                    $this->conditions_as_string = implode(' AND ', array_map(function ($condition) {
                        return "($condition)";
                    }, $this->conditions));
            }
        }

        return $this->conditions_as_string;
    }

    /**
     * Set collection conditions.
     *
     * @param  string $pattern
     * @param  array  $arguments
     * @return $this
     */
    public function &where($pattern, ...$arguments)
    {
        if (empty($pattern)) {
            throw new InvalidArgumentException('Pattern argument is required');
        }

        if (is_string($pattern)) {
            $this->conditions[] = $this->connection->prepareConditions(array_merge([$pattern], $arguments));
        } elseif (is_array($pattern)) {
            if (!empty($arguments)) {
                throw new LogicException('When pattern is an array, no extra arguments are allowed');
            }

            $this->conditions[] = $this->connection->prepareConditions($pattern);
        } else {
            throw new InvalidArgumentException('Pattern can be string or an array');
        }

        // Force rebuild of conditions as string on next getConditions() call
        $this->conditions_as_string = false;

        return $this;
    }

    // ---------------------------------------------------
    //  Joining support
    // ---------------------------------------------------

    /**
     * Name of the join table.
     *
     * @var string
     */
    private $join_table;

    /**
     * Return join table name.
     *
     * @return string
     */
    public function getJoinTable()
    {
        return $this->join_table;
    }

    /**
     * Set join table name.
     *
     * If $join_field is null, join field will be based on model name. There are two ways to specify it:
     *
     * 1. As string, where value is for target field and it will map with ID column of the source table,
     * 2. As array, where first element is ID in the source table and second element is field in target table
     *
     * @param  string            $table_name
     * @param  array|string|null $join_field
     * @return $this
     */
    public function &setJoinTable($table_name, $join_field = null)
    {
        $this->join_table = $table_name;

        if (empty($this->target_join_field)) {
            if (is_string($join_field) && $join_field) {
                $this->setTargetJoinField($join_field);
            } elseif (is_array($join_field)) {
                if (count($join_field) == 2 && !empty($join_field[0]) && !empty($join_field[1])) {
                    $this->setSourceJoinField($join_field[0]);
                    $this->setTargetJoinField($join_field[1]);
                } else {
                    throw new InvalidArgumentException('Join field should be an array with two elements');
                }
            } else {
                $registered_type = $this->getRegisteredType();

                if (($pos = strrpos($registered_type, '\\')) !== false) {
                    $this->target_join_field = Inflector::singularize(Inflector::tableize(substr($registered_type, $pos + 1))) . '_id';
                } else {
                    $this->target_join_field = Inflector::singularize(Inflector::tableize($registered_type)) . '_id';
                }
            }
        }

        return $this;
    }

    /**
     * Join field in source table.
     *
     * @var string
     */
    private $source_join_field = 'id';

    /**
     * @return string
     */
    public function getSourceJoinField()
    {
        return $this->source_join_field;
    }

    /**
     * @param  string $value
     * @return $this
     */
    public function &setSourceJoinField($value)
    {
        $this->source_join_field = $value;

        return $this;
    }

    /**
     * Join with field name.
     *
     * @var string
     */
    private $target_join_field;

    /**
     * Return join field name.
     *
     * @return string
     */
    public function getTargetJoinField()
    {
        return $this->target_join_field;
    }

    /**
     * Set join field name.
     *
     * @param  string $value
     * @return $this
     */
    public function &setTargetJoinField($value)
    {
        $this->target_join_field = $value;

        return $this;
    }

    /**
     * Return join expression.
     *
     * @return string|null
     */
    private function getJoinExpression()
    {
        if ($this->join_table && $this->target_join_field) {
            return "LEFT JOIN `$this->join_table` ON `" . $this->getTableName() . "`.`$this->source_join_field` = `$this->join_table`.`$this->target_join_field`";
        }

        return null;
    }

    /**
     * @var callable
     */
    private $pre_execute_callback;

    /**
     * Set a callback that will be triggered prior to collection execution.
     *
     * @param callable $callback
     */
    public function setPreExecuteCallback(callable $callback)
    {
        $this->pre_execute_callback = $callback;
    }
}


<?php

/**
 * Part of the Antares package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Access Control
 * @version    0.9.0
 * @author     Antares Team
 * @license    BSD License (3-clause)
 * @copyright  (c) 2017, Antares
 * @link       http://antaresproject.io
 */

namespace Antares\Acl\Processor;

use Antares\Support\Str;
use Illuminate\Support\Fluent;
use Antares\Contracts\Authorization\Factory;
use Antares\Contracts\Foundation\Foundation;

class Authorization extends Processor
{

    /**
     * ACL instance.
     *
     * @var \Antares\Contracts\Authorization\Factory
     */
    protected $acl;

    /**
     * Configuration Repository
     *
     * @var \Antares\Config\Repository
     */
    protected $config;

    /**
     * Setup a new processor.
     *
     * @param  \Antares\Contracts\Foundation\Foundation  $foundation
     * @param  \Antares\Contracts\Authorization\Factory  $acl
     */
    public function __construct(Foundation $foundation, Factory $acl)
    {
        $this->foundation = $foundation;
        $this->memory     = $foundation->memory();
        $this->acl        = $acl;
        $this->model      = $foundation->make('antares.role');
    }

    /**
     * List ACL collection.
     *
     * @param  object  $listener
     * @param  string  $metric
     *
     * @return mixed
     */
    public function edit($listener, $metric)
    {
        publish('acl', ['js/control.js']);
        $collection = [];
        $instances  = $this->acl->all();
        $eloquent   = null;

        foreach ($instances as $name => $instance) {
            $collection[$name] = $this->getAuthorizationName($name);

            $name === $metric && $eloquent = $instance;
        }

        if (is_null($eloquent)) {
            return $listener->aclVerificationFailed();
        }
        $form = $this->formBuilder->create('Antares\Acl\Http\Form\Acl', [
            'method' => 'POST',
            'url'    => route('content/save'),
            'model'  => $eloquent
        ]);

        return $listener->indexSucceed(compact('eloquent', 'collection', 'metric', 'form'));
    }

    /**
     * Update ACL metric.
     *
     * @param  object  $listener
     * @param  array   $input
     *
     * @return mixed
     */
    public function update($listener, array $input)
    {
        $all = $this->acl->all();
        if (is_null($all)) {
            return $listener->aclVerificationFailed();
        }
        $roleId = key($input['acl']);

        $role     = $this->foundation->make('antares.role')->query()->where('id', $roleId)->firstOrFail();
        $roleName = $role->name;
        $allowed  = array_keys($input['acl'][$roleId]);

        foreach ($all as $component => $details) {
            $acl     = $this->acl->get($component);
            $actions = $details->actions->get();
            foreach ($actions as $actionId => $name) {
                $allow = in_array($actionId, $allowed);
                $acl->allow($roleName, $name, $allow);
            }
            $acl->save();
        }
        return $listener->updateSucceed($roleId);
    }

    /**
     * Sync role for an ACL instance.
     *
     * @param  object  $listener
     * @param  string  $vendor
     * @param  string|null  $package
     *
     * @return mixed
     */
    public function sync($listener, $vendor, $package = null)
    {
        $roles = [];
        $name  = $this->getExtension($vendor, $package)->get('name');
        $acl   = $this->acl->get($name);

        if (is_null($acl)) {
            return $listener->aclVerificationFailed();
        }

        foreach ($this->model->all() as $role) {
            $roles[] = $role->name;
        }

        $acl->roles()->attach($roles);

        $acl->sync();

        return $listener->syncSucceed(new Fluent(compact('vendor', 'package', 'name')));
    }

    /**
     * Get extension name (if available).
     *
     * @param  string  $name
     *
     * @return string
     */
    protected function getAuthorizationName($name)
    {
        $extension = $this->memory->get("extensions.available.{$name}.name");
        $title     = ($name === 'antares') ? 'Antares' : $extension;

        return (is_null($title) ? Str::title($name) : $title);
    }

    /**
     * Get extension information.
     *
     * @param  string  $vendor
     * @param  string|null  $package
     *
     * @return \Illuminate\Support\Fluent
     */
    protected function getExtension($vendor, $package = null)
    {
        $name = (is_null($package) ? $vendor : implode('/', [$vendor, $package]));

        return new Fluent(['name' => $name, 'uid' => $name]);
    }

}


<?php
/*
 * Copyright (c) Atsuhiro Kubo <kubo@iteman.jp>,
 * All rights reserved.
 *
 * This file is part of PHPMentorsPageflowerBundle.
 *
 * This program and the accompanying materials are made available under
 * the terms of the BSD 2-Clause License which accompanies this
 * distribution, and is available at http://opensource.org/licenses/BSD-2-Clause
 */

namespace PHPMentors\PageflowerBundle\Conversation;

use PHPMentors\DomainKata\Entity\EntityInterface;
use PHPMentors\DomainKata\Specification\SpecificationInterface;

/**
 * @since Class available since Release 1.1.0
 */
class EndableConversationSpecification implements SpecificationInterface
{
    /**
     * @var bool
     */
    private $endOnNextStepOfEndPage;

    /**
     * @param bool $endOnNextStepOfEndPage
     */
    public function __construct($endOnNextStepOfEndPage)
    {
        $this->endOnNextStepOfEndPage = $endOnNextStepOfEndPage;
    }

    /**
     * {@inheritdoc}
     */
    public function isSatisfiedBy(EntityInterface $entity)
    {
        assert($entity instanceof Conversation);

        if ($entity->getCurrentPage()->isEndPage()) {
            if ($this->endOnNextStepOfEndPage) {
                if ($entity->getStepCountOnEndPage() === null) {
                    return false;
                } else {
                    return $entity->getStepCount() > $entity->getStepCountOnEndPage();
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}