<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\DependencyInjection;

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

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        // @formatter:off
        $builder
            ->root('ruwork_runet_id')
                ->beforeNormalization()
                    ->ifTrue(function ($value): bool {
                        return \is_array($value) && [] !== $value && !array_key_exists('clients', $value);
                    })
                    ->then(function (array $value): array {
                        return [
                            'clients' => [
                                'default' => $value,
                            ],
                            'default_client' => 'default',
                        ];
                    })
                ->end()
                ->children()
                    ->arrayNode('clients')
                        ->isRequired()
                        ->requiresAtLeastOneElement()
                        ->useAttributeAsKey('name')
                        ->arrayPrototype()
                            ->children()
                                ->scalarNode('key')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('secret')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('api_uri')
                                    ->cannotBeEmpty()
                                    ->defaultNull()
                                ->end()
                                ->scalarNode('oauth_uri')
                                    ->cannotBeEmpty()
                                    ->defaultNull()
                                ->end()
                                ->arrayNode('plugins')
                                    ->scalarPrototype()
                                        ->cannotBeEmpty()
                                    ->end()
                                ->end()
                                ->scalarNode('http_client')
                                    ->defaultNull()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                    ->scalarNode('default_client')
                        ->isRequired()
                        ->cannotBeEmpty()
                    ->end()
                ->end()
                ->validate()
                    ->ifTrue(function ($value): bool {
                        return \is_array($value)
                            && isset($value['default_client'])
                            && isset($value['clients'])
                            && !isset($value['clients'][$value['default_client']]);
                    })
                    ->then(function (array $value): void {
                        throw new \InvalidArgumentException(sprintf('Client "%s" is not defined and cannot be used as default.', $value['default_client']));
                    })
                ->end();
        // @formatter:on

        return $builder;
    }
}


<?php
namespace app\manage\controller;

use think\Url;
use think\Request;
use core\manage\logic\MenuLogic;
use core\manage\logic\MemberLogic;
use core\manage\logic\MemberGroupLogic;

class MemberGroup extends Base
{

    /**
     * 群组列表
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '用户群组';

        $list = MemberGroupLogic::model()->select();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 添加群组
     *
     * @param Request $request
     * @return mixed
     */
    public function addGroup(Request $request)
    {
        $group_logic = MemberGroupLogic::instance();
        if ($request->isPost()) {
            $data = [
                'group_name' => $request->param('group_name'),
                'group_info' => $request->param('group_info', ''),
                'home_page' => $request->param('home_page', ''),
                'group_status' => $request->param('group_status', 0)
            ];

            // 验证群组
            $res = $group_logic->validate->scene('add')->check($data);
            if (! $res) {
                return $this->error($group_logic->validate->getError());
            }

            // 添加群组
            $group_logic->model->add($data);

            return $this->success('添加群组成功', Url::build('memberGroup/index'));
        } else {
            $this->site_title = '新增群组';

            // 群组状态
            $group_status = $group_logic->groupStatus();
            $this->assign('group_status', $group_status);

            return $this->fetch();
        }
    }

    /**
     * 编辑群组
     *
     * @param Request $request
     * @return mixed
     */
    public function editGroup(Request $request)
    {
        $group_id = $request->param('group_id');
        if (empty($group_id)) {
            return $this->error('群组ID为空');
        }

        $group_logic = MemberGroupLogic::instance();
        if ($request->isPost()) {
            $data = [
                'group_name' => $request->param('group_name'),
                'group_info' => $request->param('group_info', ''),
                'home_page' => $request->param('home_page', ''),
                'group_status' => $request->param('group_status', 0)
            ];

            // 验证群组
            $res = $group_logic->validate->scene('edit')->check($data);
            if (! $res) {
                return $this->error($group_logic->validate->getError());
            }

            // 保存群组
            $group_logic->model->saveById($data, $group_id);

            return $this->success('修改群组成功', Url::build('memberGroup/index'));
        } else {

            $this->site_title = '编辑群组';
            $this->assign('group_id', $group_id);

            // 群组
            $group = $group_logic->model->get($group_id);
            $this->assign('group', $group);

            // 群组状态
            $group_status = $group_logic->groupStatus();
            $this->assign('group_status', $group_status);

            return $this->fetch();
        }
    }

    /**
     * 编辑权限
     *
     * @param Request $request
     * @return mixed
     */
    public function editAuth(Request $request)
    {
        $group_id = $request->param('group_id');
        if (empty($group_id)) {
            return $this->error('群组ID为空');
        }

        $group_logic = MemberGroupLogic::instance();
        if ($request->isPost()) {

            $group_menus = $request->param('group_menus/a');
            if (empty($group_menus) || count($group_menus) == 0) {
                return $this->error('权限菜单为空');
            }

            // 保存权限
            $data = [
                'group_menus' => implode(',', $group_menus)
            ];
            $group_logic->model->saveById($data, $group_id);

            return $this->success('保存权限成功', Url::build('memberGroup/index'));
        } else {

            $this->site_title = '编辑权限';
            $this->assign('group_id', $group_id);

            // 群组菜单
            $group_menus = $group_logic->getGroupMenu($group_id);
            $this->assign('group_menus', $group_menus);

            // 菜单树
            $menu_tree = MenuLogic::instance()->getMenuTree();
            $this->assign('menu_tree', $menu_tree);

            return $this->fetch();
        }
    }

    /**
     * 删除群组
     *
     * @param Request $request
     * @return mixed
     */
    public function delGroup(Request $request)
    {
        $group_id = $request->param('group_id');
        if (empty($group_id)) {
            return $this->error('群组ID为空');
        }

        // 是否有用户
        $map = [
            'group_id' => $group_id
        ];
        $record = MemberLogic::model()->where($map)
            ->field('id')
            ->find();
        if ($record) {
            return $this->error('请先移动或删除该群组下的用户');
        }

        // 删除群组
        MemberGroupLogic::model()->del($group_id);

        return $this->success('删除群组成功');
    }

    /**
     * 更改群组
     *
     * @param Request $request
     * @return mixed
     */
    public function modifyGroup(Request $request)
    {
        $id = $request->param('id');
        if (empty($id)) {
            return $this->error('ID为空');
        }

        $field_arr = [
            'group_status'
        ];
        $field = $request->param('field');
        if (! in_array($field, $field_arr)) {
            return $this->error('非法的字段');
        }

        $value = $request->param('value', '');
        MemberGroupLogic::model()->modify($id, $field, $value);

        return $this->success('更改成功');
    }
}


<?php

namespace Chill\CustomFieldsBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\Query;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Form\DataTransformer\CustomFieldsGroupToIdTransformer;
use Chill\CustomFieldsBundle\Entity\CustomFieldsDefaultGroup;

/**
 * CustomFieldsGroup controller.
 *
 */
class CustomFieldsGroupController extends Controller
{

    /**
     * Lists all CustomFieldsGroup entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $cfGroups = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->findAll();
        $defaultGroups = $this->getDefaultGroupsId();

        $makeDefaultFormViews = array();
        foreach ($cfGroups as $group) {
            if (!in_array($group->getId(), $defaultGroups)){
                $makeDefaultFormViews[$group->getId()] = $this->createMakeDefaultForm($group)->createView();
            }
        }

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:index.html.twig', array(
            'entities' => $cfGroups,
            'default_groups' => $defaultGroups,
            'make_default_forms' => $makeDefaultFormViews
        ));
    }

    /**
     * Get an array of CustomFieldsGroupId which are marked as default
     * for their entity
     *
     * @return int[]
     */
    private function getDefaultGroupsId()
    {
        $em = $this->getDoctrine()->getManager();

        $customFieldsGroupIds = $em->createQuery('SELECT g.id FROM '
                . 'ChillCustomFieldsBundle:CustomFieldsDefaultGroup d '
                . 'JOIN d.customFieldsGroup g')
                ->getResult(Query::HYDRATE_SCALAR);

        $result = array();
        foreach ($customFieldsGroupIds as $row) {
            $result[] = $row['id'];
        }

        return $result;
    }

    /**
     * create a form to make the group default
     *
     * @param CustomFieldsGroup $group
     * @return \Symfony\Component\Form\Form
     */
    private function createMakeDefaultForm(CustomFieldsGroup $group = null)
    {
        return $this->createFormBuilder($group, array(
                    'method' => 'POST',
                    'action' => $this->generateUrl('customfieldsgroup_makedefault')
                ))
                ->add('id', 'hidden')
                ->add('submit', 'submit', array('label' => 'Make default'))
                ->getForm();
    }

    /**
     * Creates a new CustomFieldsGroup entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new CustomFieldsGroup();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $this->addFlash('success', $this->get('translator')
                  ->trans("The custom fields group has been created"));

            return $this->redirect($this->generateUrl('customfieldsgroup_show', array('id' => $entity->getId())));
        }

        $this->addFlash('error', $this->get('translator')
              ->trans("The custom fields group form contains errors"));

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a CustomFieldsGroup entity.
     *
     * @param CustomFieldsGroup $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(CustomFieldsGroup $entity)
    {
        $form = $this->createForm('custom_fields_group', $entity, array(
            'action' => $this->generateUrl('customfieldsgroup_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new CustomFieldsGroup entity.
     *
     */
    public function newAction()
    {
        $entity = new CustomFieldsGroup();
        $form   = $this->createCreateForm($entity);

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a CustomFieldsGroup entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomFieldsGroup entity.');
        }

        $options = $this->getOptionsAvailable($entity->getEntity());

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:show.html.twig', array(
            'entity'      => $entity,
            'create_field_form' => $this->createCreateFieldForm($entity)->createView(),
            'options' => $options
        ));
    }

    /**
     * Return an array of available key option for custom fields group
     * on the given entity
     *
     * @param string $entity the entity to filter
     */
    private function getOptionsAvailable($entity)
    {
        $options = $this->getParameter('chill_custom_fields.'
              . 'customizables_entities');

        foreach($options as $key => $definition) {
            if ($definition['class'] == $entity) {
                foreach ($definition['options'] as $key => $value) {
                    yield $key;
                }
            }
        }
          //    [$entity->getEntity()];
    }

    /**
     * Displays a form to edit an existing CustomFieldsGroup entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomFieldsGroup entity.');
        }

        $editForm = $this->createEditForm($entity);

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a CustomFieldsGroup entity.
    *
    * @param CustomFieldsGroup $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(CustomFieldsGroup $entity)
    {
        $form = $this->createForm('custom_fields_group', $entity, array(
            'action' => $this->generateUrl('customfieldsgroup_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));
        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }

    private function createCreateFieldForm(CustomFieldsGroup $customFieldsGroup)
    {

        $fieldChoices = array();
        foreach ($this->get('chill.custom_field.provider')->getAllFields()
              as $key => $customType) {
            $fieldChoices[$key] = $customType->getName();
        }

        $customfield = (new CustomField())
              ->setCustomFieldsGroup($customFieldsGroup);

        $builder = $this->get('form.factory')
              ->createNamedBuilder(null, 'form', $customfield, array(
                    'method' => 'GET',
                    'action' => $this->generateUrl('customfield_new'),
                    'csrf_protection' => false
                    ))
              ->add('type', 'choice', array(
                    'choices' => $fieldChoices
                   ))
              ->add('customFieldsGroup', 'hidden')
              ->add('submit', 'submit');
        $builder->get('customFieldsGroup')
              ->addViewTransformer(new CustomFieldsGroupToIdTransformer(
                       $this->getDoctrine()->getManager()));

        return $builder->getForm();
    }

    /**
     * Edits an existing CustomFieldsGroup entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomFieldsGroup entity.');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            $this->addFlash('success', $this->get('translator')
                  ->trans("The custom fields group has been updated"));

            return $this->redirect($this->generateUrl('customfieldsgroup_edit', array('id' => $id)));
        }

        $this->addFlash('error', $this->get('translator')
              ->trans("The custom fields group form contains errors"));

        return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),

           ));
    }

    /**
     * Set the CustomField Group with id $cFGroupId as default
     */
    public function makeDefaultAction(Request $request)
    {

        $form = $this->createMakeDefaultForm(null);
        $form->handleRequest($request);

        $cFGroupId = $form->get('id')->getData();

        $em = $this->getDoctrine()->getManager();

        $cFGroup = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->findOneById($cFGroupId);

        if(!$cFGroup) {
            throw $this
                  ->createNotFoundException("customFieldsGroup not found with "
                        . "id $cFGroupId");
        }

        $cFDefaultGroup = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsDefaultGroup')
            ->findOneByEntity($cFGroup->getEntity());

        if($cFDefaultGroup) {
            $em->remove($cFDefaultGroup);
            $em->flush(); /*this is necessary, if not doctrine
             * will not remove old entity before adding a new one,
             * and this leads to violation constraint of unique entity
             * in postgresql
             */
        }

        $newCFDefaultGroup = new CustomFieldsDefaultGroup();
        $newCFDefaultGroup->setCustomFieldsGroup($cFGroup);
        $newCFDefaultGroup->setEntity($cFGroup->getEntity());

        $em->persist($newCFDefaultGroup);
        $em->flush();

        $this->addFlash('success', $this->get('translator')
                  ->trans("The default custom fields group has been changed"));

        return $this->redirect($this->generateUrl('customfieldsgroup'));
    }

    /**
     * This function render the customFieldsGroup as a form.
     *
     * This function is for testing purpose !
     *
     * The route which call this action is not in Resources/config/routing.yml,
     * but in Tests/Fixtures/App/app/config.yml
     *
     * @param int $id
     */
    public function renderFormAction($id, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomFieldsGroups entity.');
        }

        $form = $this->createForm('custom_field', null, array('group' => $entity));
        $form->add('submit_dump', 'submit', array('label' => 'POST AND DUMP'));
        $form->add('submit_render','submit', array('label' => 'POST AND RENDER'));
        $form->handleRequest($request);

        $this->get('twig.loader')
        ->addPath(__DIR__.'/../Tests/Fixtures/App/app/Resources/views/',
            $namespace = 'test');

        if ($form->isSubmitted()) {
            if ($form->get('submit_render')->isClicked()) {
                return $this->render('ChillCustomFieldsBundle:CustomFieldsGroup:render_for_test.html.twig', array(
                    'fields' => $form->getData(),
                    'customFieldsGroup' => $entity
                ));
            }

            var_dump($form->getData());
            var_dump(json_enccode($form->getData()));
        }

        return $this
            ->render('@test/CustomField/simple_form_render.html.twig', array(
                'form' => $form->createView()
        ));

    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Pipeline;

use Predis\CommunicationException;
use Predis\Connection\Cluster\ClusterInterface;
use Predis\Connection\ConnectionInterface;
use Predis\Connection\NodeConnectionInterface;
use Predis\NotSupportedException;

/**
 * Command pipeline that does not throw exceptions on connection errors, but
 * returns the exception instances as the rest of the response elements.
 *
 * @todo Awful naming!
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ConnectionErrorProof extends Pipeline
{
    /**
     * {@inheritdoc}
     */
    protected function getConnection()
    {
        return $this->getClient()->getConnection();
    }

    /**
     * {@inheritdoc}
     */
    protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
    {
        if ($connection instanceof NodeConnectionInterface) {
            return $this->executeSingleNode($connection, $commands);
        } elseif ($connection instanceof ClusterInterface) {
            return $this->executeCluster($connection, $commands);
        } else {
            $class = get_class($connection);

            throw new NotSupportedException("The connection class '$class' is not supported.");
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function executeSingleNode(NodeConnectionInterface $connection, \SplQueue $commands)
    {
        $responses = array();
        $sizeOfPipe = count($commands);

        foreach ($commands as $command) {
            try {
                $connection->writeRequest($command);
            } catch (CommunicationException $exception) {
                return array_fill(0, $sizeOfPipe, $exception);
            }
        }

        for ($i = 0; $i < $sizeOfPipe; ++$i) {
            $command = $commands->dequeue();

            try {
                $responses[$i] = $connection->readResponse($command);
            } catch (CommunicationException $exception) {
                $add = count($commands) - count($responses);
                $responses = array_merge($responses, array_fill(0, $add, $exception));

                break;
            }
        }

        return $responses;
    }

    /**
     * {@inheritdoc}
     */
    protected function executeCluster(ClusterInterface $connection, \SplQueue $commands)
    {
        $responses = array();
        $sizeOfPipe = count($commands);
        $exceptions = array();

        foreach ($commands as $command) {
            $cmdConnection = $connection->getConnectionByCommand($command);

            if (isset($exceptions[spl_object_hash($cmdConnection)])) {
                continue;
            }

            try {
                $cmdConnection->writeRequest($command);
            } catch (CommunicationException $exception) {
                $exceptions[spl_object_hash($cmdConnection)] = $exception;
            }
        }

        for ($i = 0; $i < $sizeOfPipe; ++$i) {
            $command = $commands->dequeue();

            $cmdConnection = $connection->getConnectionByCommand($command);
            $connectionHash = spl_object_hash($cmdConnection);

            if (isset($exceptions[$connectionHash])) {
                $responses[$i] = $exceptions[$connectionHash];
                continue;
            }

            try {
                $responses[$i] = $cmdConnection->readResponse($command);
            } catch (CommunicationException $exception) {
                $responses[$i] = $exception;
                $exceptions[$connectionHash] = $exception;
            }
        }

        return $responses;
    }
}


<?php

namespace Versatile\View;

use Versatile\View\Contracts\ModelPresenter;
use Collection\Support\FindsCallableByInheritance;
use ReflectionClass;

class ModelPresenterRegistry implements ModelPresenter
{

    use FindsCallableByInheritance;

    /**
     * {@inheritdoc}
     *
     * @param object $object
     * @return int|string
     **/
    public function id($object)
    {
        if ($provider = $this->nearestForClass(get_class($object), 'id')) {
            return call_user_func($provider, $object);
        }
        return '';
    }

    /**
     * {@inheritdoc}
     *
     * @param object $object
     * @param string $view (optional)
     * @return string
     **/
    public function shortName($object, $view=self::VIEW_DEFAULT)
    {
        if ($provider = $this->nearestForClass(get_class($object), 'shortName')) {
            return call_user_func($provider, $object, $view);
        }
        return '';
    }

    /**
     * {@inheritdoc}
     *
     * @param string $class
     * @param string $view (optional)
     * @return array Just an indexed array of key names ([id, name, address.street])
     **/
    public function keys($class, $view=self::VIEW_DEFAULT)
    {
        if ($provider = $this->nearestForClass($class, 'keys')) {
            return call_user_func($provider, $class, $view);
        }
        return [];
    }

    /**
     * {@inheritdoc}
     *
     * @param string $class
     * @param string $view (optional)
     * @return array Just an indexed array of key names ([id, name, address.street])
     **/
    public function searchableKeys($class, $view=self::VIEW_DEFAULT)
    {
        if ($provider = $this->nearestForClass($class, 'searchableKeys')) {
            return call_user_func($provider, $class, $view);
        }
        return [];
    }

    /**
     * Add a callable which will handling getting the id for class $class
     *
     * @param string $class
     * @param callable $provider
     * @return self
     **/
    public function provideId($class, callable $provider)
    {
        $this->addCallable($class, $provider, 'id');
        return $this;
    }

    /**
     * Add a callable which will handling getting the shortName for class $class
     *
     * @param string $class
     * @param callable $provider
     * @return self
     **/
    public function provideShortName($class, callable $provider)
    {
        $this->addCallable($class, $provider, 'shortName');
        return $this;
    }

    /**
     * Add a callable which will handling getting the keys for class $class
     *
     * @param string $class
     * @param callable $provider
     * @return self
     **/
    public function provideKeys($class, callable $provider)
    {
        $this->addCallable($class, $provider, 'keys');
        return $this;
    }

    /**
     * Add a callable which will handling getting the searchableKeys for $class
     *
     * @param string $class
     * @param callable $provider
     * @return self
     **/
    public function provideSearchableKeys($class, callable $provider)
    {
        $this->addCallable($class, $provider, 'searchableKeys');
        return $this;
    }

}


<?php

/**
 * Manage Cache by Apc
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Cache;
use \Venus\lib\Cache\CacheInterface;

/**
 * This class manage the Cache by Apc
 *
 * @category  	lib
 * @package		lib\Cache
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Apc implements CacheInterface
{
	/**
	 * set a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  mixed $mValue value of this sesion var
	 * @param  int $iFlag unused
	 * @param  int $iExpire expiration of cache
	 * @return \Venus\lib\Cache\Apc
	 */
	public function set(string $sName, $mValue, int $iFlag = 0, int $iExpire = 0)
	{
		apc_add($sName, $mValue, $iExpire);
		return $this;
	}

	/**
	 * get a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  int $iFlags flags
	 * @param  int $iTimeout expiration of cache
	 * @return mixed
	 */
	public function get(string $sName, int &$iFlags = null, int $iTimeout = 0)
	{
		return apc_fetch($sName);
	}

	/**
	 * delete a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @return mixed
	 */
	public function delete(string $sName)
	{
		return apc_delete($sName);
	}

	/**
	 * flush the cache
	 *
	 * @access public
	 * @return mixed
	 */
	public function flush()
	{
		return flush();
	}
}


<?php

namespace OpenOrchestra\ModelBundle\Repository\RepositoryTrait;

/**
 * Trait UseTrackableTrait
 */
trait UseTrackableTrait
{
    /**
     * @param string $entityId
     * @param string $entityType
     *
     * @return array
     */
    public function findByUsedInEntity($entityId, $entityType)
    {
        $qb = $this->createQueryBuilder();

        $qb->field('useReferences.' . $entityType . '.' . $entityId)->exists('true');

        return $qb->getQuery()->execute();
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Block;
use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\TinyMCEWysiwygStrategy;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelBundle\Document\Area;

/**
 * Class CommunityDataGenerator
 */
class CommunityDataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeEn()
    {
        $htmlContent = <<<EOF

Community

We invite you to follow the Open Orchestra community across these different way of communication :

To contribute and follow our change : Github

To ask technical questions : Google group

To follows news about the product : Twitter

For more information : Official Website

EOF;
        $name = "Community";
        $language = "en";
        $routePattern = "page-community";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
         $htmlContent = <<<EOF

Communauté

Nous vous invitons à suivre la communauté Open Orchestra à travers nos différents canaux de communication:

Pour contribuer et suivre nos modifications : Github

Pour poser vos questions techniques : Google group

Pour suivre l'actualité de la plateforme : Twitter

Pour plus de renseignements : Site officiel

EOF;
        $name = "Communauté";
        $language = "fr";
        $routePattern = 'page-communaute';

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeDe()
    {
        $htmlContent = <<<EOF

Gemeinde

Wir laden Sie zu der Open Orchestra Gemeinschaft durch unsere verschiedenen Kommunikationskanäle zu folgen :

Einen Beitrag zu leisten und füllen Sie Änderungen : Github

Technische Fragen : Google group

Für die neuesten Plattform : Twitter

Weitere Informationen : Offizielle Website

EOF;
        $name = "Gemeinde";
        $language = "de";
        $routePattern = 'seite-gemeinde';

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @param string $htmlContent
     * @param string $name
     * @param string $language
     * @param string $routePattern
     *
     * @return Node
     */
    protected function generateNodeGlobal($htmlContent, $name, $language, $routePattern)
    {
        $nodeCommunityBlock = new Block();
        $nodeCommunityBlock->setLabel('Wysiwyg');
        $nodeCommunityBlock->setLanguage($language);
        $nodeCommunityBlock->setComponent(TinyMCEWysiwygStrategy::NAME);
        $nodeCommunityBlock->setAttributes(array(
            "htmlContent" => $htmlContent
        ));

        $nodeCommunityBlock = $this->generateBlock($nodeCommunityBlock);

        $main = new Area();
        $main->addBlock($nodeCommunityBlock);

        $nodeCommunity = $this->createBaseNode();
        $nodeCommunity->setArea('main', $main);

        $nodeCommunity->setNodeId('fixture_page_community');
        $nodeCommunity->setLanguage($language);
        $nodeCommunity->setName($name);
        $nodeCommunity->setVersionName($this->getVersionName($nodeCommunity));
        $nodeCommunity->setParentId(NodeInterface::ROOT_NODE_ID);
        $nodeCommunity->setOrder(3);
        $nodeCommunity->setRoutePattern($routePattern);
        $nodeCommunity->setInFooter(false);
        $nodeCommunity->setInMenu(true);

        return $nodeCommunity;
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Temporary.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Material;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\Exceptions\InvalidArgumentException;
use EasyWeChat\Support\File;

/**
 * Class Temporary.
 */
class Temporary extends AbstractAPI
{
    /**
     * Allow media type.
     *
     * @var array
     */
    protected $allowTypes = ['image', 'voice', 'video', 'thumb'];

    const API_GET = 'https://api.weixin.qq.com/cgi-bin/media/get';
    const API_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/media/upload';

    /**
     * Download temporary material.
     *
     * @param string $mediaId
     * @param string $directory
     * @param string $filename
     *
     * @return string
     *
     * @throws InvalidArgumentException
     */
    public function download($mediaId, $directory, $filename = '')
    {
        if (!is_dir($directory) || !is_writable($directory)) {
            throw new InvalidArgumentException("Directory does not exist or is not writable: '$directory'.");
        }

        $filename = $filename ?: $mediaId;

        $stream = $this->getStream($mediaId);

        $filename .= File::getStreamExt($stream);

        file_put_contents($directory.'/'.$filename, $stream);

        return $filename;
    }

    /**
     * Fetch item from WeChat server.
     *
     * @param string $mediaId
     *
     * @return mixed
     *
     * @throws \EasyWeChat\Core\Exceptions\RuntimeException
     */
    public function getStream($mediaId)
    {
        $response = $this->getHttp()->get(self::API_GET, ['media_id' => $mediaId]);

        $response->getBody()->rewind();

        $body = $response->getBody()->getContents();

        $json = json_decode($body, true);

        if (JSON_ERROR_NONE === json_last_error()) {
            $this->checkAndThrow($json);
        }

        return $body;
    }

    /**
     * Upload temporary material.
     *
     * @param string $type
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function upload($type, $path)
    {
        if (!file_exists($path) || !is_readable($path)) {
            throw new InvalidArgumentException("File does not exist, or the file is unreadable: '$path'");
        }

        if (!in_array($type, $this->allowTypes, true)) {
            throw new InvalidArgumentException("Unsupported media type: '{$type}'");
        }

        return $this->parseJSON('upload', [self::API_UPLOAD, ['media' => $path], [], ['type' => $type]]);
    }

    /**
     * Upload image.
     *
     * @param $path
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function uploadImage($path)
    {
        return $this->upload('image', $path);
    }

    /**
     * Upload video.
     *
     * @param $path
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function uploadVideo($path)
    {
        return $this->upload('video', $path);
    }

    /**
     * Upload voice.
     *
     * @param $path
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function uploadVoice($path)
    {
        return $this->upload('voice', $path);
    }

    /**
     * Upload thumb.
     *
     * @param $path
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function uploadThumb($path)
    {
        return $this->upload('thumb', $path);
    }
}


<?php
namespace Lab123\Odin\Command;

use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Symfony\Component\Finder\Finder;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;

class LumenAppNameCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'app:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set the application namespace';

    /**
     * The Composer class instance.
     *
     * @var \Illuminate\Support\Composer
     */
    protected $composer;

    /**
     * The filesystem instance.
     *
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;

    /**
     * Current root application namespace.
     *
     * @var string
     */
    protected $currentRoot;

    /**
     * Actual namespace application.
     *
     * @var string
     */
    protected $namespace = 'App';

    /**
     * Create a new key generator command.
     *
     * @param \Illuminate\Support\Composer $composer
     * @param \Illuminate\Filesystem\Filesystem $files
     * @return void
     */
    public function __construct(Composer $composer, Filesystem $files)
    {
        parent::__construct();

        $this->files = $files;
        $this->composer = $composer;
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        //$this->currentRoot = trim($this->laravel->getNamespace(), '\\');
        $this->currentRoot = trim($this->namespace, '\\');

        $this->setBootstrapNamespaces();

        $this->setAppDirectoryNamespace();

        $this->setConfigNamespaces();

        $this->setComposerNamespace();

        $this->setDatabaseFactoryNamespaces();

        $this->info('Application namespace set!');

        $this->composer->dumpAutoloads();

        //$this->call('clear-compiled');
    }

    /**
     * Set the namespace on the files in the app directory.
     *
     * @return void
     */
    protected function setAppDirectoryNamespace()
    {
        $files = Finder::create()->in($this->laravel['path'])->name('*.php');

        foreach ($files as $file) {
            $this->replaceNamespace($file->getRealPath());
        }
    }

    /**
     * Replace the App namespace at the given path.
     *
     * @param string $path
     * @return void
     */
    protected function replaceNamespace($path)
    {
        $search = [
            'namespace ' . $this->currentRoot . ';',
            $this->currentRoot . '\\'
        ];

        $replace = [
            'namespace ' . $this->argument('name') . ';',
            $this->argument('name') . '\\'
        ];

        $this->replaceIn($path, $search, $replace);
    }

    /**
     * Set the bootstrap namespaces.
     *
     * @return void
     */
    protected function setBootstrapNamespaces()
    {
        $search = [
            $this->currentRoot . '\\Http',
            $this->currentRoot . '\\Console',
            $this->currentRoot . '\\Exceptions'
        ];

        $replace = [
            $this->argument('name') . '\\Http',
            $this->argument('name') . '\\Console',
            $this->argument('name') . '\\Exceptions'
        ];

        $this->replaceIn($this->getBootstrapPath(), $search, $replace);
    }

    /**
     * Set the PSR-4 namespace in the Composer file.
     *
     * @return void
     */
    protected function setComposerNamespace()
    {
        $this->replaceIn($this->getComposerPath(), str_replace('\\', '\\\\', $this->currentRoot) . '\\\\', str_replace('\\', '\\\\', $this->argument('name')) . '\\\\');
    }

    /**
     * Set the namespace in the appropriate configuration files.
     *
     * @return void
     */
    protected function setConfigNamespaces()
    {
        $this->setAppConfigNamespaces();

        $this->setAuthConfigNamespace();

        $this->setServicesConfigNamespace();
    }

    /**
     * Set the application provider namespaces.
     *
     * @return void
     */
    protected function setAppConfigNamespaces()
    {
        $search = [
            $this->currentRoot . '\\Providers',
            $this->currentRoot . '\\Http\\Controllers\\'
        ];

        $replace = [
            $this->argument('name') . '\\Providers',
            $this->argument('name') . '\\Http\\Controllers\\'
        ];

        //$this->replaceIn($this->getConfigPath('app'), $search, $replace);
    }

    /**
     * Set the authentication User namespace.
     *
     * @return void
     */
    protected function setAuthConfigNamespace()
    {
        //$this->replaceIn($this->getConfigPath('auth'), $this->currentRoot . '\\User', $this->argument('name') . '\\User');
    }

    /**
     * Set the services User namespace.
     *
     * @return void
     */
    protected function setServicesConfigNamespace()
    {
        //$this->replaceIn($this->getConfigPath('services'), $this->currentRoot . '\\User', $this->argument('name') . '\\User');
    }

    /**
     * Set the namespace in database factory files.
     *
     * @return void
     */
    protected function setDatabaseFactoryNamespaces()
    {
        $this->replaceIn($this->laravel->databasePath() . '/factories/ModelFactory.php', $this->currentRoot, $this->argument('name'));
    }

    /**
     * Replace the given string in the given file.
     *
     * @param string $path
     * @param string|array $search
     * @param string|array $replace
     * @return void
     */
    protected function replaceIn($path, $search, $replace)
    {
        $this->files->put($path, str_replace($search, $replace, $this->files->get($path)));
    }

    /**
     * Get the path to the bootstrap/app.php file.
     *
     * @return string
     */
    protected function getBootstrapPath()
    {
        //return $this->laravel->bootstrapPath() . '/app.php';
        return 'bootstrap/app.php';
    }

    /**
     * Get the path to the Composer.json file.
     *
     * @return string
     */
    protected function getComposerPath()
    {
        return $this->laravel->basePath() . '/composer.json';
    }

    /**
     * Get the path to the given configuration file.
     *
     * @param string $name
     * @return string
     */
    protected function getConfigPath($name)
    {
        dd('Não existem os recursos');
        return $this->laravel['path.config'] . '/' . $name . '.php';
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            [
                'name',
                InputArgument::REQUIRED,
                'The desired namespace.'
            ]
        ];
    }
}


<?php

namespace bariew\eventModule;

class Module extends \yii\base\Module
{
    public $params = [
        'menu'  => [
            'label' => 'Settings',
            'items' => [[
                'label'    => 'Events',
                'url' => ['/event/item/index']
            ]]
        ]
    ];

    /**
     * Checks whether current module is enabled.
     * @return bool
     */
    public static function isEnabled()
    {
        $class = self::className();
        foreach (\Yii::$app->modules as $module => $params) {
            switch (gettype($params)) {
                case 'array' : if ($class == @$params['class']) return true;
                    break;
                case 'object': if ($class == get_class($params)) return true;
                    break;
                default : if ($class == $params) return true;
            }
            if ($module == $class || (isset($module['class']) && $module['class'] == $class)) {
                return true;
            }
        }
        return false;
    }
}


<?php declare(strict_types=1);
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

namespace Gears\Asset\Minifiers;

use SplFileInfo;
use Gears\String\Str;
use Gears\Asset\Contracts\Minifier;

abstract class Base implements Minifier
{
    /**
     * This contains the source code to be minfied.
     *
     * @var string
     */
    protected $source;

    /**
     * We represent the source file that needs to be minified.
     *
     * @var SplFileInfo
     */
    protected $file;

    public function __construct(SplFileInfo $file, string $source)
    {
        $this->file = $file;
        $this->source = $source;
    }

    public function minify(): string
    {
        $min = $this->lookForPreMinifiedAsset();

        if ($min === false)
        {
            return $this->mini();
        }

        return $min;
    }

    /**
     * This must be defined in any child classes.
     *
     * @return string The minfied source code.
     */
    abstract protected function mini(): string;

    /**
     * If we can find a pre-minified version of the file lets use that,
     * no point doing more work than we have to. Plus the vendor supplied
     * minified versions will probably be better optimised.
     *
     * @return string|bool Either preminified source code or false.
     */
    private function lookForPreMinifiedAsset()
    {
        $min_path = (string)Str::s($this->file->getRealPath())->replace
        (
            '.'.$this->file->getExtension(),
            '.min.'.$this->file->getExtension()
        );

        if (!file_exists($min_path)) return false;

        return file_get_contents($min_path);
    }
}


<?php
/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */

namespace VinceT\AdminBundle\Theme;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */
class ThemeHandler implements ContainerAwareInterface
{
    protected $container = null;
    private $_default = null;
    private $_themes = null;

    /**
     * [__construct description]
     *
     * @param ContainerInterface $container [description]
     */
    public function __construct(ContainerInterface $container)
    {
        $this->setContainer($container);
        $this->_getThemes();
    }

    /**
     * Sets the Container.
     *
     * @param ContainerInterface $container A ContainerInterface instance
     *
     * @return null
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Gets a Theme by its identifier
     *
     * @param string $identifier Theme identifier
     *
     * @return Theme
     */
    public function getTheme($identifier)
    {
        $themes = $this->getAvailableThemes();
        if ( !isset($themes[$identifier]) ) {
            $themeIds = array();
            foreach ($themes as $key => $value) {
                $themeIds[] = $key;
            }
            throw new \Exception(sprintf('Theme "%s" does not exist. Possible values are [%s]', $identifier, implode(', ', $themeIds)), 1);
        }
        return $themes[$identifier];
    }

    /**
     * Gets the default theme to use
     *
     * @return string
     */
    public function getDefaultTheme()
    {
        $config = $this->_getThemeConfig();
        return $this->getTheme($config['default_theme']);
    }

    /**
     * Gets the current theme used
     *
     * @return Theme
     */
    public function getCurrentTheme()
    {
        $theme = $this->getDefaultTheme();
        if ( $this->container->get('session')->has('_admin_theme') ) {
            $theme = $this->container->get('session')->get('_admin_theme');
        }
        return $theme;
    }

    /**
     * Sets the current theme
     *
     * @param string $identifier [description]
     *
     * @return null
     */
    public function setCurrentTheme($identifier)
    {
        $theme = $this->getTheme($identifier);
        $this->container->get('session')->set('_admin_theme', $theme);
    }

    /**
     * Gets the URI for a file
     *
     * @param string $file [description]
     *
     * @return string
     */
    public function getUri($file)
    {
        return $this->getCurrentTheme()->getBasePath().'/'.$file;
    }

    /**
     * Gets the available themes
     *
     * @return array
     */
    public function getAvailableThemes()
    {
        return $this->_getThemes();
    }

    /**
     * Gets the theme config
     *
     * @return array
     */
    private function _getThemeConfig()
    {
        return $this->container->getParameter('vince_t.admin.theme');
    }

    /**
     * Gets themes
     *
     * @return array
     */
    private function _getThemes()
    {
        if ( is_null($this->_themes) ) {
            $config = $this->_getThemeConfig();
            $this->_themes = array();
            foreach ($config['themes'] as $identifier => $conf) {
                $t = new Theme();
                $t->setIdentifier($identifier);
                $t->setName($conf['name']);
                $t->setBasePath($conf['base_path']);
                $this->_themes[$identifier] = $t;
            }
            if ( count($this->_themes) == 0 ) {
                $t = new Theme();
                $t->setIdentifier('default');
                $t->setName('Default');
                $t->setBasePath('bundles/vincetadmin/bootstrap/default');
                $this->_themes['default'] = $t;
            }
        }
        return $this->_themes;
    }

}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Bonus;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusBase\Repo\Data\Log\Customers as ELogCust;
use Praxigento\BonusBase\Repo\Data\Log\Opers as ELogOper;
use Praxigento\BonusHybrid\Config as Cfg;

/**
 * Calculate Infinity Bonus.
 */
class Infinity
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** Calculation scheme (DEFAULT or EU) */
    const CTX_IN_SCHEME = 'in.scheme';

    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper */
    private $hlpOper;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans */
    private $hlpTrans;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Customers */
    private $daoLogCust;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Opers */
    private $daoLogOper;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Infinity\Calc */
    private $subCalc;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusBase\Repo\Dao\Log\Customers $daoLogCust,
        \Praxigento\BonusBase\Repo\Dao\Log\Opers $daoLogOper,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans $hlpTrans,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper $hlpOper,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Infinity\Calc $subCalc
    ) {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->daoCalc = $daoCalc;
        $this->daoLogCust = $daoLogCust;
        $this->daoLogOper = $daoLogOper;
        $this->servPeriodGet = $servPeriodGet;
        $this->hlpTrans = $hlpTrans;
        $this->hlpOper = $hlpOper;
        $this->subCalc = $subCalc;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* get working data from context */
        $scheme = $ctx->get(self::CTX_IN_SCHEME) ?? Cfg::SCHEMA_DEFAULT;
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Override bonus ('$scheme' scheme) is started.");
        /**
         * get dependent calculation data
         *
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $infPeriod
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $infCalc
         */
        list($compressCalc, $infPeriod, $infCalc) = $this->getCalcData($scheme);
        $compressCalcId = $compressCalc->getId();
        $infCalcId = $infCalc->getId();
        /* calculate bonus */
        $bonus = $this->subCalc->exec($compressCalcId, $infCalcId, $scheme);
        /* convert calculated bonus to transactions */
        $trans = $this->getTransactions($bonus, $infPeriod);
        /* register bonus operation */
        $operRes = $this->hlpOper->exec(Cfg::CODE_TYPE_OPER_BONUS_INFINITY, $trans, $infPeriod);
        $operId = $operRes->getOperationId();
        $transIds = $operRes->getTransactionsIds();
        /* register transactions in log */
        $this->saveLogCustomers($transIds);
        /* register operation in log */
        $this->saveLogOper($operId, $infCalcId);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($infCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Override bonus ('$scheme' scheme) is completed.");
    }

    /**
     * Get period and calculation data for all related calculation types.
     *
     * @return array [$compressCalc, $infPeriod, $infCalc]
     * @throws \Exception
     */
    private function getCalcData($scheme)
    {
        if ($scheme == Cfg::SCHEMA_EU) {
            $baseTypeCode = Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_EU;
            $depTypeCode = Cfg::CODE_TYPE_CALC_BONUS_INFINITY_EU;
        } else {
            $baseTypeCode = Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_DEF;
            $depTypeCode = Cfg::CODE_TYPE_CALC_BONUS_INFINITY_DEF;
        }
        /**
         * Get period & calc data for Infinity bonus based on Phase2 Compression.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode($baseTypeCode);
        $req->setDepCalcTypeCode($depTypeCode);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Period $infPeriod */
        $infPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $infCalc */
        $infCalc = $resp->getDepCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $infPeriod, $infCalc];
        return $result;
    }

    /**
     * @param array $bonus [custId => bonusValue]
     * @param \Praxigento\BonusBase\Repo\Data\Period $period
     * @return \Praxigento\Accounting\Repo\Data\Transaction[]
     */
    private function getTransactions($bonus, $period)
    {
        $dsEnd = $period->getDstampEnd();
        $dateApplied = $this->hlpPeriod->getTimestampUpTo($dsEnd);
        $yyyymm = substr($dsEnd, 0, 6);
        $note = "Infinity ($yyyymm)";
        $result = $this->hlpTrans->exec($bonus, $dateApplied, $note);
        return $result;
    }

    /**
     * Save customers log for Team bonus transactions (DEFAULT scheme).
     *
     * @param array $transIds [$transId => $custId]
     */
    private function saveLogCustomers($transIds)
    {
        foreach ($transIds as $transId => $custId) {
            $this->daoLogCust->create([
                ELogCust::A_TRANS_ID => $transId,
                ELogCust::A_CUSTOMER_ID => $custId

            ]);
        }
    }

    /**
     * Bind operation with calculation.
     *
     * @param int $operId
     * @param int $calcId
     */
    private function saveLogOper($operId, $calcId)
    {
        $entity = new ELogOper();
        $entity->setOperId($operId);
        $entity->setCalcId($calcId);
        $this->daoLogOper->create($entity);
    }

}


<?php
namespace Lab123\Odin;

abstract class FieldManager
{

    /**
     * General rules to validate this request.
     *
     * @var $rules
     */
    protected $fields = [];

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules($extraRules = [])
    {
        $rules = $this->getRules();

        /* Adiciona as regras extras as regras padrão do objeto */
        foreach ($extraRules as $field => $rule) {

            if (! key_exists($this->getOnlyField($field), $rules)) {
                continue;
            }

            /* Ajuste para validação de array */
            if (strpos($field, '.') > -1) {

                $rules[$field] = $rules[$this->getOnlyField($field)] . '|' . $rule;
                unset($rules[$this->getOnlyField($field)]);
                continue;
            }

            $rules[$field] .= '|' . $rule;
        }

        return $this->transformToFrontName($rules);
    }

    private function getOnlyField($string)
    {
        $array = explode('.', $string);

        return end($array);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    private function getRules()
    {
        $rules = [];
        foreach ($this->fields as $field => $extra) {
            if (! key_exists('rules', $extra)) {
                continue;
            }

            $rules[$field] = $extra['rules'];
        }

        return $rules;
    }

    /**
     * Transform attributes model.
     *
     * @return array
     */
    public function transformToResource(array $array = [])
    {
        if (count($array) < 1) {
            return $array;
        }

        $transformation = array_reverse($this->getTransformation());
        $transformed = [];

        foreach ($transformation as $name => $new_name) {
            if (! key_exists($name, $array)) {

                if (key_exists($new_name, $array)) {
                    $transformed[$name] = $array[$new_name];
                }
                continue;
            }

            $transformed[$new_name] = $array[$name];
        }

        return $transformed;
    }

    /**
     * Transform attributes model.
     *
     * @return array
     */
    public function transformToFrontName(array $array = [])
    {
        $transformed = [];
        $transformation = $this->getTransformation();

        if (key_exists('public_id', $array)) {
            $transformed['id'] = $array['public_id'];
        }

        foreach ($transformation as $name => $new_name) {

            if (! key_exists($name, $array)) {

                foreach ($array as $field => $rule) {
                    if ($this->getOnlyField($field) == $name) {
                        $transformed[$field] = $array[$field];
                    }
                }
                continue;
            }

            $transformed[$new_name] = $array[$name];
        }

        return $transformed;
    }

    /**
     * Get the transformation data
     *
     * @return array
     */
    private function getTransformation()
    {
        $transforms = [];
        foreach ($this->fields as $field => $extra) {
            if (is_int($field)) {
                $transforms[$extra] = $extra;
                continue;
            }

            $transform = (key_exists('transform', $extra)) ? $extra['transform'] : $field;

            if ($transform === false) {
                continue;
            }

            $transforms[$field] = $transform;
        }

        return $transforms;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function getAutocomplete()
    {
        $autocomplete = [];
        foreach ($this->fields as $field => $extra) {
            if (! key_exists('autocomplete', $extra)) {
                continue;
            }

            $autocomplete[] = $field;
        }

        return $autocomplete;
    }

    /**
     * Validate store action
     *
     * @return array
     */
    public function store()
    {
        return $this->rules();
    }

    /**
     * Validate update action
     *
     * @return array
     */
    public function update()
    {
        return $this->rules();
    }

    /**
     * Validate update action
     *
     * @return array
     */
    public function associate()
    {
        return [];
    }

    /**
     * Validate update action
     *
     * @return array
     */
    public function autocomplete()
    {
        return [
            'text' => ''
        ];
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Bridge\ElFinder;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Exception\General\InvalidArgumentException;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * The object assigned to handle a base elFinder connector
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\ElFinder
 */
abstract class ElFinderConnector implements ElFinderConnectorInterface
{
    /**
     * @type null|ConfigurationHandler
     */
    protected $configurationHandler = null;
    /**
     * @type array
     */
    protected $options = array();
    /**
     * @type bool
     */
    private $connectorLoaded = false;

    /**
     * Constructor
     */
    public function __construct(ConfigurationHandler $configurationHandler, OptionsResolver $optionsResolver = null)
    {
        $this->configurationHandler = $configurationHandler;
        if (null === $optionsResolver) {
            $optionsResolver = new OptionsResolver();
        }

        $optionsResolver->setRequired(
            array(
                'folder',
                'alias',
            )
        );

        $configuration = $this->configure();
        $optionsResolver->resolve($configuration);

        $this->options = $this->generateOptions($configuration["folder"], $configuration["alias"]);
    }

    /**
     * Starts the elFinder connector
     *
     * @codeCoverageIgnore
     */
    public function connect()
    {
        $this->loadConnectors();
        $connector = new \elFinderConnector(new \elFinder($this->options));
        $connector->run();
    }

    /**
     * Generates the elFinder options
     *
     * @param string $folder
     * @param string $rootAlias
     * @return array
     */
    private function generateOptions($folder, $rootAlias)
    {
        $assetsPath = $this->configurationHandler->uploadAssetsDir() . '/' . $folder;
        if (!is_dir($assetsPath)) {
            @mkdir($assetsPath);
        }

        $options = array(
            'locale' => '',
            'roots' => array(
                array(
                    'driver' => 'LocalFileSystem',
                    // driver for accessing file system (REQUIRED)
                    'path' => $assetsPath,
                    // path to files (REQUIRED)
                    'URL' => $this->configurationHandler->absoluteUploadAssetsDir() . '/' . $folder,
                    // URL to files (REQUIRED)
                    'accessControl' => 'access',
                    // disable and hide dot starting files (OPTIONAL)
                    'rootAlias' => $rootAlias
                    // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }

    /**
     * @codeCoverageIgnore
     */
    private function loadConnectors()
    {
        if ($this->connectorLoaded) {
            return;
        }

        $webDir = $this->configurationHandler->webDir();
        require_once $webDir . '/components/redkitecms/elfinder/php/elFinderConnector.class.php';
        require_once $webDir . '/components/redkitecms/elfinder/php/elFinder.class.php';
        require_once $webDir . '/components/redkitecms/elfinder/php/elFinderVolumeDriver.class.php';
        require_once $webDir . '/components/redkitecms/elfinder/php/elFinderVolumeLocalFileSystem.class.php';

        $this->connectorLoaded = true;
    }
}


<?php
/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Project\Loader;

use Generator;
use Skyline\Compiler\CompilerContext;
use Skyline\Compiler\Exception\ProjectLoaderException;
use SimpleXMLElement;
use Skyline\Compiler\Project\Attribute\Attribute;
use Skyline\Compiler\Project\Attribute\CompilerContextParameterCollection;
use Skyline\Compiler\Project\Attribute\FilterAttribute;
use Skyline\Compiler\Project\Attribute\FilterConditionAttribute;

class XML extends AbstractFileLoader
{
    private $XML;

    /**
     * @inheritDoc
     */
    protected function getProjectRootDirectory(): string
    {
        return (string) $this->XML->directory;
    }

    /**
     * @inheritDoc
     */
    protected function getProjectInstanceClass(): string
    {
        return (string) $this->XML['class'];
    }

    protected function getConstructorArguments(): ?array
    {
        $arguments = [];
        if($args = $this->XML->argument) {
            foreach($args as $arg) {
                $arguments[] = $this->getXMLElementValue($arg);
            }
        }
        return $arguments;
    }

    /**
     * @inheritDoc
     */
    protected function loadDidBegin()
    {
        libxml_clear_errors();
        $xml = @simplexml_load_file($this->getFilename());
        $error = libxml_get_last_error();
        if($error) {
            $e = new ProjectLoaderException($error->message);
            $e->setLoader($this);
            throw $e;
        }
        $this->XML = $xml;
    }

    /**
     * @inheritDoc
     */
    protected function yieldAttributes(): Generator
    {
        if($attributes = $this->XML->attributes->attr) {
            foreach($attributes as $attr) {
                $name = (string)$attr["name"];
                $value = self::getXMLElementValue($attr);

                yield $name => $value;
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function yieldSearchPaths(): Generator
    {
        if($searchPaths = $this->XML->searchPaths->dir) {
            foreach($searchPaths as $path) {
                $type = (string)$path["type"];
                $value = (string)$path;

                yield $type => $value;
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function yieldCrossOriginResourceSharingHosts(): Generator
    {
        if($hosts = $this->XML->CORS->host) {

            foreach($hosts as $host) {
                $name = (string)$host["name"];
                $accepts = [];
                foreach($host->accepts as $acc) {
                    $accepts[] = (string) $acc;
                }

                yield new Attribute($name, $accepts);
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function yieldWhitelistAccess(): Generator
    {
        if($whitelist = $this->XML->whitelist->ip) {
            foreach ($whitelist as $white) {
                yield (string)$white;
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function yieldFilters(): Generator
    {
        if($filterList = $this->XML->filter) {
            $filters = [];
            /** @var SimpleXMLElement $filter */
            foreach ($filterList as $filter) {
                $action = "";
                if($redir = $filter["redirect"] ?? NULL)
                    $action = "header(\"Location: $redir\")";

                if(!$action) {
                    trigger_error("Filter does not provide a known action", E_USER_NOTICE);
                    continue;
                }

                $filters[] = $FILTER = new FilterAttribute('redirect', $action);
                $conds = [];

                $concat = " || ";
                if(strtolower($filter["operator"]) == 'and')
                    $concat = " && ";

                $FILTER->setConditionConcat($concat);

                foreach ($filter->children() as $child) {
                    $bank = $child["bank"] ?? "_SERVER";
                    $name = $child->getName();

                    $cond = new FilterConditionAttribute($name, (string) $child, $bank);

                    $mods = explode(" ", $child["mode"]);
                    $modifiers = 0;
                    foreach($mods as $mod) {
                        if($mod) {
                            switch (strtolower($mod)) {
                                case "not":
                                    $modifiers |= FilterConditionAttribute::NOT_MODIFIER;
                                    break;
                                default:
                                    trigger_error("Unknown modifier $mod", E_USER_NOTICE);
                            }
                        }
                    }

                    $cond->setModifier($modifiers);
                    $conds[] = $cond;
                }

                $FILTER->setConditions($conds);
                yield $FILTER;
            }
        }
    }

    /**
     * @inheritDoc
     */
    protected function loadCompilerContextParameters(CompilerContextParameterCollection $parameterCollection)
    {
        if($ctx = $this->XML->context) {
            $parameterCollection->setContextClass((string) ($ctx["class"] ?? CompilerContext::class));
            $parameterCollection->setBootstrapClass( (string) ($ctx->bootstrap ?? NULL) );
            $parameterCollection->setApplicationClass( (string) ($ctx->application ?? NULL) );

            if($ctx->factory) {
                $factories = [];
                foreach($ctx->factory as $f) {
                    $factories[] = (string) $f;
                }

                $parameterCollection->setCompilerFactories($factories);
            }

            if(isset($ctx->denyModifications))
                $parameterCollection->denyModifications();
        }
    }

    /**
     * Unpacks an XML element into a value <... type="string|int|bool|float|list">....</...>
     * While the type list expects children like <item key="a key">...</item>
     *
     * @param \SimpleXMLElement $element
     * @return bool|float|int|string|array
     */
    public static function getXMLElementValue(SimpleXMLElement $element, string $forceType = NULL, bool $forceAll = false) {
        $normalize = function(SimpleXMLElement $element, $forced) use (&$normalize, $forceAll) {
            $type = (string) ($element['type'] ?? 'string');
            if($forced)
                $type = $forced;

            if($type == 'list') {
                $list = [];
                foreach($element->children() as $child) {
                    $key = (string)$child["key"];
                    $value = $normalize($child, $forceAll ? $forced : "");

                    if($key)
                        $list[$key] = $value;
                    else
                        $list[] = $value;
                }
                return $list;
            }

            $value = (string) $element;
            switch ($type) {
                case 'int': return (int) $value;
                case 'float': return (float) $value;
                case 'bool': return (bool) $value;
                default: break;
            }
            return $value;
        };

        return $normalize($element, $forceType);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\Theme;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Plugin\Plugin;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\Utils;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

/**
 * Class ThemeBase is the object assigned to handle Theme base methods and properties
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Theme
 */
abstract class ThemeBase
{
    /**
     * @type \RedKiteCms\Plugin\Plugin
     */
    protected $theme;
    /**
     * @type string
     */
    protected $baseThemeDir;
    /**
     * @type string
     */
    protected $themeDir;
    /**
     * @type string
     */
    protected $templatesDir;
    /**
     * @type array
     */
    //protected $templateSlots;
    /**
     * @type bool
     */
    protected $booted = false;

    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    protected $configurationHandler;
    /**
     * @type array
     */
    protected $templates;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
    }

    /**
     * Boots the theme
     * @param \RedKiteCms\Plugin\Plugin $theme
     *
     * @return $this
     */
    public function boot(Plugin $theme)
    {
        if ($this->booted && $this->theme == $theme) {
            return $this;
        }

        $this->theme = $theme;
        $pluginDir = $this->theme->getPluginDir();
        $this->baseThemeDir = $this->themeDir = $pluginDir . '/Resources/theme';
        if ($this->configurationHandler->isTheme()) {
            $this->themeDir .= '_dev';
        }
        $this->templatesDir = $pluginDir . '/Resources/views';
        if (!is_dir($this->themeDir)) {
            mkdir($this->themeDir);
        }

        $this->templates = $this->findTemplates();
        $this->booted = true;

        return $this;
    }

    public function templates()
    {
        return array_keys($this->templates["template"]);
    }

    /**
     * Finds the theme's templates
     * @param null|int $depth When null parses all subfolders
     *
     * @return array
     */
    private function findTemplates()
    {
        $templates = array(
            "base" => array(),
            "template" => array(),
        );
        $finder = new Finder();
        $files = $finder->files()->in($this->templatesDir);
        foreach ($files as $file) {
            $file = (string)$file;
            $templateName = basename($file, '.html.twig');

            $key = 'template';
            if (str_replace($this->templatesDir . '/', '', $file) != $templateName . '.html.twig') {
                $key = 'base';
            }
            $templates[$key][$templateName] = $file;
        }

        return $templates;
    }

    /**
     * Find the slots parsing the theme's templates
     *
     * @return array
     */
    protected function findSlotsInTemplates()
    {
        $templates = $this->findTemplates();
        $slots = array();
        foreach ($templates["base"] as $templateName => $templateFile) {
            $templateContents = FilesystemTools::readFile($templateFile);
            $slots = array_merge_recursive($slots, $this->findSlots($templateName, $templateContents));
        }
        $baseSlots["base"] = $slots;

        $slots = array();
        foreach ($templates["template"] as $templateName => $templateFile) {
            $templateContents = FilesystemTools::readFile($templateFile);
            $slots[$templateName] = $this->findSlots($templateName, $templateContents);
        }

        return array(
            'base' => $baseSlots,
            'templates' => $slots,
        );
    }

    /**
     * Parses the given template to find slots
     * @param string $templateName
     * @param string $templateContents
     *
     * @return array
     */
    protected function findSlots($templateName, $templateContents)
    {
        // find repeated slots
        preg_match_all(
            '/\{#[\s]?repeat:[\s]?(site|language)[^\}]+[^\{]+\{\{[\s]+?slots.([^|]+)?/is',
            $templateContents,
            $matches,
            PREG_SET_ORDER
        );
        $slots = array();
        $rawSlots = array();
        foreach ($matches as $slot) {
            $repeat = $slot[1];
            $slotName = $slot[2];
            $slots[$repeat][] = $slotName;
            $rawSlots[] = $slotName;
        }

        // find all slots
        preg_match_all('/\{\{[\s]+?slots.([^|]+)?/is', $templateContents, $matches);
        $pageSlots = array_diff($matches[1], $rawSlots);
        //$this->templateSlots[$templateName] = $pageSlots;
        if (empty($pageSlots)) {
            return $slots;
        }

        $slots["page"] = $pageSlots;

        return $slots;
    }

    protected function mergeSlots($templateSlots)
    {
        $allSlots = array();
        foreach($templateSlots as $slot) {
            $allSlots = array_merge($allSlots, $slot);
        }

        return $allSlots;
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Rendering\Controller\Page;

use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class PermalinksController is the object assigned to list the website permalinks
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Page
 */
abstract class PermalinksController extends BasePageController
{
    /**
     * Implements the action to list the website permalink
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listPermalinks(array $options)
    {
        $permalinks = $options["pages_collection_parser"]
            ->contributor($options["username"])
            ->parse()
            ->permalinksByLanguage();

        $permalinksList = array();
        foreach ($permalinks as $permalink) {
            $permalinksList[] = array(
                'title' => $permalink,
                'value' => $permalink,
            );
        }

        return $this->buildJSonResponse($permalinksList);
    }

    /**
     * Configures the base options for the resolver
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(
            array(
                'request',
                'pages_collection_parser',
                'username',
            )
        );

        $resolver->setAllowedTypes(
            array(
                'request' => '\Symfony\Component\HttpFoundation\Request',
                'pages_collection_parser' => '\RedKiteCms\Content\PageCollection\PagesCollectionParser',
                'username' => array(
                    'null',
                    'string',
                ),
            )
        );
    }
}


<?php

namespace ObjectivePHP\Package\Doctrine;

use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\UnderscoreNamingStrategy;
use Doctrine\ORM\Tools\Setup;
use ObjectivePHP\Application\Package\PackageInterface;
use ObjectivePHP\Application\Workflow\PackagesInitListener;
use ObjectivePHP\Application\Workflow\WorkflowEventInterface;
use ObjectivePHP\Package\Doctrine\Config\EntityManager as EM;
use ObjectivePHP\Config\ConfigAccessorsTrait;
use ObjectivePHP\Config\ConfigInterface;
use ObjectivePHP\Config\ConfigProviderInterface;
use ObjectivePHP\Primitives\String\Str;
use ObjectivePHP\Config\Config;
use ObjectivePHP\ServicesFactory\ServicesFactory;

/**
 * Class DoctrinePackage
 * @package Fei\Service\SecondPartyLogistics\Tool\Package\Doctrine
 */
class DoctrinePackage implements PackageInterface, ConfigProviderInterface, PackagesInitListener
{
    use ConfigAccessorsTrait;

    const SERVICE_PREFIX = 'doctrine.em.';

    /**
     * {@inheritdoc}
     */
    public function getConfig(): ConfigInterface
    {
        return new Config(new EM());
    }

    /**
     * {@inheritdoc}
     */
    public function onPackagesInit(WorkflowEventInterface $event)
    {
        $this->registerServices(
            $event->getApplication()->getServicesFactory(),
            $event->getApplication()->getConfig()->get(EM::KEY)
        );
    }

    /**
     * Register Connection and EntityManager Services
     *
     * @param ServicesFactory $servicesFactory
     * @param EM[]            $entityManagers
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \ObjectivePHP\ServicesFactory\Exception\ServicesFactoryException
     */
    public function registerServices(ServicesFactory $servicesFactory, array $entityManagers)
    {
        foreach ($entityManagers as $name => $entityManager) {
            //TODO: handle isDev depending on app config
            $emConfig = Setup::createAnnotationMetadataConfiguration(
                (array) $entityManager->getEntities(),
                true,
                null,
                null,
                true
            );

            $emConfig->setNamingStrategy(new UnderscoreNamingStrategy());

            $em = $this->createEntityManager($entityManager->toArray(), $emConfig);

            // register entity manager as a service
            $emServiceId = 'doctrine.em.' . Str::cast($name)->lower();

            $servicesFactory->registerService(['id' => $emServiceId, 'instance' => $em]);
            $servicesFactory->registerService([
                'id' => 'db.connection.' . $name,
                'instance' => $em->getConnection()->getWrappedConnection()
            ]);
        }
    }

    /**
     * Factory for create a Doctrine EntityManager instance
     *
     * @param mixed         $conn   An array with the connection parameters or an existing Connection instance.
     * @param Configuration $config
     *
     * @return EntityManager
     * @throws \Doctrine\ORM\ORMException
     */
    protected function createEntityManager($conn, Configuration $config)
    {
        return EntityManager::create($conn, $config);
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Override;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Cfg\Override as ECfgOvrd;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Override\Calc\Entry as DEntry;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Data\Bonus as DBonus;
use Praxigento\Downline\Repo\Data\Customer as ECustomer;

class Calc
{
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Cfg\Override */
    private $daoCfgOvrd;
    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Rank */
    private $daoRank;
    /** @var \Praxigento\Core\Api\Helper\Format */
    private $hlpFormat;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpTree;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Format $hlpFormat,
        \Praxigento\Downline\Api\Helper\Tree $hlpTree,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme,
        \Praxigento\Downline\Repo\Dao\Customer $daoDwnl,
        \Praxigento\BonusBase\Repo\Dao\Rank $daoRank,
        \Praxigento\BonusHybrid\Repo\Dao\Cfg\Override $daoCfgOvrd,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl
    )
    {
        $this->logger = $logger;
        $this->hlpFormat = $hlpFormat;
        $this->hlpTree = $hlpTree;
        $this->hlpScheme = $hlpScheme;
        $this->daoDwnl = $daoDwnl;
        $this->daoRank = $daoRank;
        $this->daoCfgOvrd = $daoCfgOvrd;
        $this->daoBonDwnl = $daoBonDwnl;
    }

    /**
     * @param $custId int Customer ID
     * @param $cfgOvr array override bonus configuration parameters for the customer
     * @param $mapGen array generations mapping
     * @param $mapById array customer data by ID mapping
     *
     * @return number
     */
    private function calcOverrideBonusByRank($custId, $cfgOvr, $mapGen, $mapById)
    {
        $result = [];
        if (isset($mapGen[$custId])) {
            $generations = $mapGen[$custId];
            /* this customer has generations in downline */
            /**
             * @var int $gen
             * @var ECfgOvrd $cfgData
             */
            foreach ($cfgOvr as $gen => $cfgData) {
                $percent = $cfgData->getPercent();
                if ($percent > 0) {
                    if (isset($generations[$gen])) {
                        /* this generation exists for the customer */
                        $team = $mapGen[$custId][$gen];
                        foreach ($team as $childId) {
                            /** @var EBonDwnl $childData */
                            $childData = $mapById[$childId];
                            $pv = $childData->getPv();
                            $bonus = $this->hlpFormat->roundBonus($pv * $percent);
                            $this->logger->debug("Customer #$custId has '$pv' PV for '$gen' generation and '$bonus' as override bonus part from child #$childId .");
                            $resultEntry = new DBonus();
                            $resultEntry->setCustomerRef($custId);
                            $resultEntry->setDonatorRef($childId);
                            $resultEntry->setValue($bonus);
                            $result[] = $resultEntry;
                        }
                    }
                }
            }
        }
        return $result;
    }

    public function exec($compressCalcId, $scheme)
    {
        $result = [];
        /* collect additional data */
        $dwnlCompress = $this->daoBonDwnl->getByCalcId($compressCalcId);
        $dwnlPlain = $this->daoDwnl->get();
        $cfgOverride = $this->getCfgOverride();
        /* create maps to access data */
        $mapCmprsById = $this->hlpTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF);
        $mapPlainById = $this->hlpTree->mapById($dwnlPlain, ECustomer::A_CUSTOMER_REF);
        $mapTeams = $this->hlpTree->mapByTeams($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF);
        /* populate compressed data with depth & path values */
        $mapByDepthDesc = $this->hlpTree->mapByTreeDepthDesc($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_DEPTH);
        /* scan all levels starting from the bottom and collect PV by generations */
        $mapGenerations = $this->mapByGeneration($mapByDepthDesc,
            $mapCmprsById); // [ $custId=>[$genId => $totalPv, ...], ... ]
        /* 'distributor' is the minimal rank in compressed trees */
        $defRankId = $this->daoRank->getIdByCode(Cfg::RANK_DISTRIBUTOR);
        /* scan all customers and calculate bonus values */
        /** @var EBonDwnl $custCompress */
        foreach ($dwnlCompress as $custCompress) {
            $custId = $custCompress->getCustomerRef();
            $rankId = $custCompress->getRankRef();
            /** @var ECustomer $custPlain */
            $custPlain = $mapPlainById[$custId];
            $custRef = $custPlain->getMlmId();
            $custScheme = $this->hlpScheme->getSchemeByCustomer($custPlain);
            if (
                ($rankId != $defRankId) &&
                ($custScheme == $scheme)
            ) {
                /* this is qualified manager */
                $this->logger->debug("Customer #$custId (#$custRef ) from scheme '$custScheme' is qualified to rank #$rankId.");
                if (isset($cfgOverride[$scheme][$rankId])) {
                    $cfgOvrEntry = $cfgOverride[$scheme][$rankId];
                    // calculate bonus value for $custId according rank configuration
                    $bonusData = $this->calcOverrideBonusByRank($custId, $cfgOvrEntry, $mapGenerations, $mapCmprsById);
                    /* ... and add to result set */
                    $entry = new DEntry();
                    $entry->setCustomerRef($custId);
                    $entry->setRankRef($rankId);
                    $entry->setEntries($bonusData);
                    $result[] = $entry;
                } else {
                    /* this rank is not qualified to the bonus */
                }
            }
        }
        unset($mapGenerations);
        unset($mapByDepthDesc);
        unset($mapTreeExp);
        unset($mapTeams);
        unset($mapCmprsById);
        /* convert 2D array with results into plain array */
        $result = $this->plainBonus($result);
        return $result;
    }

    /**
     * @return array [$scheme][$rankId][$gen] => $cfg;
     */
    private function getCfgOverride()
    {
        $result = [];
        $data = $this->daoCfgOvrd->get();
        /** @var ECfgOvrd $one */
        foreach ($data as $one) {
            $scheme = $one->getScheme();
            $rankId = $one->getRankId();
            $gen = $one->getGeneration();
            $result[$scheme][$rankId][$gen] = $one;
        }
        return $result;
    }

    /**
     * Generate map of the customer generations.
     *
     * @param $mapByDepthDesc
     * @param $mapById
     * @param $mapById
     *
     * @return array [$custId=>[$genNum=>[$childId, ...], ...], ...]
     */
    private function mapByGeneration($mapByDepthDesc, $mapById)
    {
        $result = []; // [ $custId=>[$genId => $totalPv, ...], ... ]
        foreach ($mapByDepthDesc as $depth => $ids) {
            foreach ($ids as $custId) {
                /** @var EBonDwnl $entry */
                $entry = $mapById[$custId];
                $path = $entry->getPath();
                $parents = $this->hlpTree->getParentsFromPathReversed($path);
                $level = 0;
                foreach ($parents as $parentId) {
                    $level += 1;
                    if (!isset($result[$parentId])) {
                        $result[$parentId] = [];
                    }
                    if (!isset($result[$parentId][$level])) {
                        $result[$parentId][$level] = [];
                    }
                    $result[$parentId][$level][] = $custId;
                }
            }
        }
        return $result;
    }

    /**
     * Convert 2D array with bonuses into 1D array.
     *
     * @param $bonus
     * @return array
     */
    private function plainBonus($bonus)
    {
        /* prepare data for updates */
        $result = [];
        /** @var DEntry $item */
        foreach ($bonus as $item) {
            $bonusData = $item->getEntries();
            /** @var DBonus $entry */
            foreach ($bonusData as $entry) {
                $bonus = $entry->getValue();
                if ($bonus > Cfg::DEF_ZERO) {
                    $result[] = $entry;
                }
            }
        }
        return $result;
    }

}