<?php

/*
 * Copyright (c) 2012-2014 Alessandro Siragusa <alessandro@togu.io>
 *
 * This file is part of the Togu CMS.
 *
 * Togu is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Togu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Togu.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Togu\AdminBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\View\View;
use \JMS\Serializer\SerializationContext;
use \Doctrine\DBAL\DBALException;
use \JMS\Serializer\DeserializationContext;
use FOS\RestBundle\Controller\Annotations\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class EntitiesController
 */
class EntitiesController extends FOSRestController {
    /**
     * Get detail of a record
     * @param              $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @QueryParam(name="group", description="The JMS Serializer group", default="")
     * @QueryParam(name="depth", description="The depth to use for serialization", default="1")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getEntityAction(ParamFetcherInterface $paramFetcher, $id) {
    	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
        $manager = $this->get("doctrine_phpcr.odm.default_document_manager");
        $entity = $manager->getRepository($modelLoader->getFullClassName($entityName))->find($id);
        $view = View::create(array(
        	"success" => $entity !== null,
        	"total" => $entity !== null ? 1 : 0,
        	"records" => array($entity)
        ), 200)->setSerializationContext($this->getSerializerContext(array("get")));;
        return $this->handleView($view);
    }

    /**
     * Get list of records
     * @param ParamFetcherInterface $paramFetcher
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @QueryParam(name="page", requirements="\d+", default="1", description="Page of the list.")
     * @QueryParam(name="start", requirements="\d+", default="0", description="Offset of the list")
     * @QueryParam(name="limit", requirements="\d+", default="25", description="Number of record per fetch.")
     * @QueryParam(name="sort", description="Sort result by field in URL encoded JSON format", default="[]")
     * @QueryParam(name="filter", description="Search filter in URL encoded JSON format", default="[]")
     * @QueryParam(name="gridFilter", description="Search filter in URL encoded JSON format", default="[]")
     * @QueryParam(name="group", description="The JMS Serializer group", default="")
     * @QueryParam(name="depth", description="The depth to use for serialization", default="1")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getEntitiesAction(ParamFetcherInterface $paramFetcher) {
    	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
    	$manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $rawSorters = json_decode($paramFetcher->get("sort"), true);
        $sorters = array();
        foreach ($rawSorters as $s) {
            $sorters[$s['property']] = $s['direction'];
        }
        $rawFilters = json_decode($paramFetcher->get("filter"), true);
        $filters = array();
        foreach ($rawFilters as $f) {
            $filters[$f['property']] = $f['value'];
        }
        $rawGridFilters = json_decode($paramFetcher->get("gridFilter"), true);
        foreach ($rawGridFilters as $f) {
        	$comparator = isset($f['comparison']) ? $f['comparison'] : 'eq';
        	$filters[$f['field']] = array(
        		$comparator => $f['value']
        	);
        }
        $start = 0;
        if ($paramFetcher->get("start") === "0") {
            if ($paramFetcher->get("page") > 1) {
                $start = ($paramFetcher->get("page")-1) * $paramFetcher->get("limit");
            }
        } else {
            $start = $paramFetcher->get("start");
        }
        $repository = $manager->getRepository($modelLoader->getFullClassName($entityName));
        $list = $repository->findBy(
            $filters,
            $sorters,
            $paramFetcher->get("limit"),
            $start
        );
        $count = $repository->findBy(
        	$filters
        );

        $list = array_values($list->toArray());
        $context = $this->getSerializerContext(array('list'));
        $view = View::create(array(
        	"success" => true,
        	"records" =>  $list,
        	"total" => count($count)
        ), 200)->setSerializationContext($context);
        return $this->handleView($view);
    }

    /**
     * Create a new record
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function postEntitiesAction(ParamFetcherInterface $paramFetcher) {
       	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
    	$serializer = $this->get("tpg_extjs.phpcr_serializer");
        $entity = $serializer->deserialize(
            $this->getRequest()->getContent(),
        	$modelLoader->getFullClassName($entityName),
            'json',
            DeserializationContext::create()->setGroups(array("Default", "post"))
        );
        $validator = $this->get('validator');
        $validations = $validator->validate($entity, array('Default', 'post'));
        if ($validations->count() === 0) {
            $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
            $rootData = $manager->find(null, '/data');
            $entity->setParentDocument($rootData);
            $manager->persist($entity);
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
		        	"success" => $entity !== null,
		        	"total" => $entity !== null ? 1 : 0,
		        	"records" => array($entity)
		        ), 201, array('Location'=>$this->generateUrl(
                    "_togu_admin_bundle_api_get_entities",
                    array('id'=>$entity->getId()),
                    true
                )))->setSerializationContext($this->getSerializerContext())
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Update an existing record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function putEntitiesAction(ParamFetcherInterface $paramFetcher, $id) {
       	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
    	$manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository($modelLoader->getFullClassName($entityName))->find($id);
        if ($entity === null) {
            return $this->handleView(View::create('', 404));
        }
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $entity = $serializer->deserialize(
            $this->getRequest()->getContent(),
            $modelLoader->getFullClassName($entityName),
            'json',
            DeserializationContext::create()->setGroups(array("Default", "put"))
        );
        $validator = $this->get('validator', array('Default', 'put'));
        $validations = $validator->validate($entity);
        if ($validations->count() === 0) {
            try {
                $manager->merge($entity);
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
		        	"success" => $entity !== null,
		        	"total" => $entity !== null ? 1 : 0,
		        	"records" => array($entity)
		        ), 200)->setSerializationContext($this->getSerializerContext(array("get")))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Patch an existing record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function patchEntitiesAction(ParamFetcherInterface $paramFetcher, $id) {
       	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
    	$manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository($modelLoader->getFullClassName($entityName))->find($id);
        if ($entity === null) {
            return $this->handleView(View::create('', 404));
        }
        $content = json_decode($this->getRequest()->getContent(), true);
        $content['id'] = $id;
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $dContext = DeserializationContext::create()->setGroups(array("Default", "patch"));
        $dContext->attributes->set('related_action', 'merge');
        $entity = $serializer->deserialize(
            json_encode($content),
            $modelLoader->getFullClassName($entityName),
            'json',
            $dContext
        );
        $validator = $this->get('validator');
        $validations = $validator->validate($entity, array('Default', 'patch'));
        if ($validations->count() === 0) {
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
		        	"success" => $entity !== null,
		        	"total" => $entity !== null ? 1 : 0,
		        	"records" => array($entity)
		        ), 200)->setSerializationContext($this->getSerializerContext(array("get")))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Delete an existing record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="entity", description="EntityName", default="")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function deleteEntitiesAction(ParamFetcherInterface $paramFetcher, $id) {
       	$entityName = $paramFetcher->get("entity");
    	$modelLoader = $this->get("togu.generator.model.config");
    	if(! $modelLoader->hasModel($entityName)) {
    		throw new NotFoundHttpException("Entity $entityName is not defined");
    	}
    	$manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository($modelLoader->getFullClassName($entityName))->find($id);
        $manager->remove($entity);
        $manager->flush();
        return $this->handleView(View::create(null, 204));
    }

    protected function getSerializerContext($groups = array(), $version = null) {
        $serializeContext = SerializationContext::create();
        $serializeContext->enableMaxDepthChecks();
        $serializeContext->setGroups(array_merge(
            array(\JMS\Serializer\Exclusion\GroupsExclusionStrategy::DEFAULT_GROUP),
            $groups
        ));
        if ($version !== null) $serializeContext->setVersion($version);
        return $serializeContext;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: ColumnBool.php 3687 2011-04-12 19:58:36Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;

//include_once("ColumnText.php");

/**
 * ColumnBool class is element for ColumnBool
 * show boolean on data list (table)
 *
 * @package openbiz.bin.easy.element
 * @author wangdong1984
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class ColumnShare extends ColumnText
{

    public $myPrivateImg = null;
    public $mySharedImg = null;
    public $myAssignedImg = null;
    public $myDistributedImg = null;
    public $groupSharedImg = null;
    public $otherSharedImg = null;
    public $defaultImg = null;
    public $recordOwnerId = null;
    public $recordGroupId = null;
    public $recordGroupPerm = null;
    public $recordOtherPerm = null;
    public $recordCreatorId = null;
    protected $recordOwnerId_AutoLoad = false;
    protected $recordGroupId_AutoLoad = false;
    protected $recordGroupPerm_AutoLoad = false;
    protected $recordOtherPerm_AutoLoad = false;
    public $hasOwnerField = false;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->myPrivateImg = isset($xmlArr["ATTRIBUTES"]["MYPRIVATEIMG"]) ? $xmlArr["ATTRIBUTES"]["MYPRIVATEIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_private.gif";
        $this->mySharedImg = isset($xmlArr["ATTRIBUTES"]["MYSHAREDIMG"]) ? $xmlArr["ATTRIBUTES"]["MYSHAREDIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_shared.gif";
        $this->myAssignedImg = isset($xmlArr["ATTRIBUTES"]["MYASSIGNEDIMG"]) ? $xmlArr["ATTRIBUTES"]["MYASSIGNEDIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_assigned.gif";
        $this->myDistributedImg = isset($xmlArr["ATTRIBUTES"]["MYDISTRIBUTEDIMG"]) ? $xmlArr["ATTRIBUTES"]["MYDISTRIBUTEDIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_distributed.gif";
        $this->groupSharedImg = isset($xmlArr["ATTRIBUTES"]["GROUPSHAREDIMG"]) ? $xmlArr["ATTRIBUTES"]["GROUPSHAREDIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_shared_group.gif";
        $this->otherSharedImg = isset($xmlArr["ATTRIBUTES"]["OTHERSHAREDIMG"]) ? $xmlArr["ATTRIBUTES"]["OTHERSHAREDIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_shared_other.gif";
        $this->defaultImg = isset($xmlArr["ATTRIBUTES"]["DEFAULTIMG"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTIMG"] : "{OPENBIZ_RESOURCE_URL}/common/images/icon_data_shared_other.gif";

        $this->recordCreatorId = isset($xmlArr["ATTRIBUTES"]["CREATORID"]) ? $xmlArr["ATTRIBUTES"]["CREATORID"] : null;
        $this->recordOwnerId = isset($xmlArr["ATTRIBUTES"]["OWNERID"]) ? $xmlArr["ATTRIBUTES"]["OWNERID"] : null;
        $this->recordGroupId = isset($xmlArr["ATTRIBUTES"]["GROUPID"]) ? $xmlArr["ATTRIBUTES"]["GROUPID"] : null;
        $this->recordGroupPerm = isset($xmlArr["ATTRIBUTES"]["GROUPPERM"]) ? $xmlArr["ATTRIBUTES"]["GROUPPERM"] : null;
        $this->recordOtherPerm = isset($xmlArr["ATTRIBUTES"]["OTHERPERM"]) ? $xmlArr["ATTRIBUTES"]["OTHERPERM"] : null;

        $this->recordOwnerId_AutoLoad = isset($xmlArr["ATTRIBUTES"]["OWNERID"]) ? false : true;
        $this->recordGroupId_AutoLoad = isset($xmlArr["ATTRIBUTES"]["GROUPID"]) ? false : true;
        $this->recordGroupPerm_AutoLoad = isset($xmlArr["ATTRIBUTES"]["GROUPPERM"]) ? false : true;
        $this->recordOtherPerm_AutoLoad = isset($xmlArr["ATTRIBUTES"]["OTHERPERM"]) ? false : true;
    }

    public function setValue($value)
    {
        $formObj = $this->getFormObj();
        $rec = $formObj->getActiveRecord();

        if ($this->recordOwnerId_AutoLoad) {
            $this->hasOwnerField = $this->_hasOwnerField();
            if ($this->hasOwnerField) {
                $this->recordOwnerId = $rec['owner_id'];
                $this->recordCreatorId = $rec['create_by'];
            } else {
                $this->recordOwnerId = $rec['create_by'];
            }
        }

        if ($this->recordGroupId_AutoLoad) {
            $this->recordGroupId = $rec['group_id'];
        }

        if ($this->recordGroupPerm_AutoLoad) {
            $this->recordGroupPerm = $rec['group_perm'];
        }

        if ($this->recordOtherPerm_AutoLoad) {
            $this->recordOtherPerm = $rec['other_perm'];
        }
    }

    public function getValue()
    {
        $user_id = Openbizx::$app->getUserProfile("Id");
        $groups = Openbizx::$app->getUserProfile("groups");
        if (!$groups)
            $groups = array();

        $this->hasOwnerField = $this->_hasOwnerField();
        if ($this->hasOwnerField) {

            if ($this->recordOwnerId != $this->recordCreatorId) {
                if ($this->recordOwnerId == $user_id) {
                    $this->value = 4;
                    return $this->value;
                } elseif ($this->recordCreatorId == $user_id) {
                    $this->value = 5;
                    return $this->value;
                }
            }
        }

        if ($user_id == $this->recordOwnerId) {
            if ((int) $this->recordGroupPerm > 0 || (int) $this->recordOtherPerm > 0) {

                $this->value = 1;
            } else {
                $this->value = 0;
            }
        } elseif ($this->recordOtherPerm > 0) {
            $this->value = 3;
        } else {
            foreach ($groups as $group_id) {
                if ($group_id == $this->recordGroupId) {
                    $this->value = 2;
                    break;
                }
            }
        }

        return $this->value;
    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $style = $this->getStyle();
        $text = $this->getText();
        $id = $this->objectName;
        $func = $this->getFunction();

        switch ($this->getValue()) {
            case "0":
                $image_url = $this->myPrivateImg;
                break;
            case "1":
                $image_url = $this->mySharedImg;
                break;
            case "2":
                $image_url = $this->groupSharedImg;
                break;
            case "3":
                $image_url = $this->otherSharedImg;
                break;
            case "4":
                $image_url = $this->myAssignedImg;
                break;
            case "5":
                $image_url = $this->myDistributedImg;
                break;
            default:
                if ($this->defaultImg == '{OPENBIZ_RESOURCE_URL}/common/images/icon_data_shared_other.gif') {
                    $this->defaultImg = $this->otherSharedImg;
                }
                $image_url = $this->defaultImg;
                break;
        }

        if (preg_match("/\{.*\}/si", $image_url)) {
            $formobj = $this->getFormObj();
            $image_url = Expression::evaluateExpression($image_url, $formobj);
        } else {
            $image_url = Openbizx::$app->getImageUrl() . "/" . $image_url;
        }
        if ($this->width) {
            $width = "width=\"$this->width\"";
        }
        if ($this->link) {
            $link = $this->getLink();
            $target = $this->getTarget();
            $sHTML = "";
        } else {
            $sHTML = "";
        }
        return $sHTML;
    }

    private function _hasOwnerField()
    {
        $field = $this->getFormObj()->getDataObj()->getField('owner_id');
        if ($field) {
            return true;
        } else {
            return false;
        }
    }

}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @licennse   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: FormRenderer.php 4075 2011-05-02 13:43:39Z jixian2003 $
 */

namespace Openbizx\Easy;

use Openbizx\Openbizx;
use Openbizx\Helpers\TemplateHelper;

/**
 * FormRenderer class is form helper for rendering form
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2011
 * @access public
 */
class FormRenderer
{

    /**
     * Render form object
     *
     * @param EasyForm $formObj
     * @return string result of rendering process
     */
    static public function render($formObj)
    {
        $tplEngine = $formObj->templateEngine;
        $tplAttributes = FormRenderer::buildTemplateAttributes($formObj);
        if (isset($formObj->jsClass)) {
            $subForms = ($formObj->subForms) ? implode(";", $formObj->subForms) : "";

            if ($formObj->staticOutput != true) {
                $formScript = "\n<script>Openbizx.newFormObject('$formObj->objectName','$formObj->jsClass','$subForms'); </script>\n";
            }
            if ($formObj->autoRefresh > 0) {
                $formScript .= "\n<script>setTimeout(\"Openbizx.CallFunction('$formObj->objectName.UpdateForm()');\",\"" . ($formObj->autoRefresh * 1000) . "\") </script>\n";
            }
        }

        if ($tplEngine == "Smarty" || $tplEngine == null) {
            return FormRenderer::renderSmarty($formObj, $tplAttributes) . $formScript;
        } else
            return FormRenderer::renderPHP($formObj, $tplAttributes) . $formScript;
    }

    /**
     * Gather all template variables needed. Should play well with Smarty or \Zend templates
     *
     * @param WebPage $formObj
     * @return array associative array holding all needed VIEW based template variables
     */
    static public function buildTemplateAttributes($formObj)
    {
        // Assocative Array to hold all Template Values
        // Fill with default viewobj attributes
        $tplAttributes = array();

        $tplAttributes['title'] = $formObj->title;
        $tplAttributes['errors'] = $formObj->errors;
        $tplAttributes['notices'] = $formObj->notices;
        $tplAttributes['formname'] = $formObj->objectName;
        $tplAttributes['module'] = $formObj->getModuleName($formObj->objectName);

        // if the $formobj form type is list render table, otherwise render record
        if (strtoupper($formObj->formType) == 'LIST') {
            $recordSet = $formObj->fetchDataSet();
            $tplAttributes['dataPanel'] = $formObj->dataPanel->renderTable($recordSet);
        } else {
            $record = $formObj->fetchData();
            $tplAttributes['dataPanel'] = $formObj->dataPanel->renderRecord($record);
        }

        if (isset($formObj->searchPanel)) {
            $search_record = $formObj->searchPanelValues;
            foreach ($formObj->searchPanel as $elem) {
                if (!$elem->fieldName) {
                    continue;
                }
                $post_value = Openbizx::$app->getClientProxy()->getFormInputs($elem->objectName);
                if ($post_value) {
                    $search_record[$elem->fieldName] = $post_value;
                }
            }
            $tplAttributes['searchPanel'] = $formObj->searchPanel->renderRecord($search_record);
        } else {
            $tplAttributes['searchPanel'] = $formObj->searchPanel->render();
        }
        $tplAttributes['actionPanel'] = $formObj->actionPanel->render();
        $tplAttributes['navPanel'] = $formObj->navPanel->render();

        if (isset($formObj->wizardPanel)) {
            $tplAttributes['wizardPanel'] = $formObj->wizardPanel->render();
        }
        $tplAttributes['form'] = $formObj->outputAttrs();

        return $tplAttributes;
    }

    /**
     * Render smarty template for form object
     *
     * @param EasyForm $formObj
     * @param string $tplFile
     * @return string result of rendering process
     */
    static protected function renderSmarty($formObj, $tplAttributes = Array())
    {
        $smarty = TemplateHelper::getSmartyTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($formObj->templateFile, $formObj->package);

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            $smarty->assign($key, $value);
        };

        return $smarty->fetch($tplFile);
    }

    /**
     * Render PHP template for form object
     *
     * @param EasyForm $formObj
     * @param string $tplFile
     * @return string result of rendering process
     */
    static protected function renderPHP($formObj, $tplAttributes = Array())
    {
        $form = TemplateHelper::getZendTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($formObj->templateFile, $formObj->package);
        $form->addScriptPath(dirname($tplFile));

        /* $formOutput = $formObj->outputAttrs();
          foreach ($formOutput as $k=>$v) {
          $form->$k = $v;
          } */

        foreach ($tplAttributes as $key => $value) {
            if ($value == NULL) {
                $form->$key = '';
            } else {
                $form->$key = $value;
            }
        }

        // render the formobj attributes
        //$form->form = $formOutput;

        return $form->render($formObj->templateFile);
    }

}

?>


<?php

namespace CatLab\Charon\Laravel\Controllers;

use CatLab\Charon\Collections\ResourceCollection;
use CatLab\Charon\Enums\Action;
use CatLab\Charon\Exceptions\ResourceException;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\ResourceDefinition;
use CatLab\Charon\Laravel\Database\Model;
use CatLab\Charon\Laravel\Exceptions\EntityNotFoundException;
use CatLab\Charon\Models\ResourceResponse;
use CatLab\Charon\Models\RESTResource;
use CatLab\Requirements\Exceptions\ResourceValidationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Trait CRUDController
 *
 * This trait contains some basic functionality to easily set up a laravel crud controller.
 * Any class using this trait must also use the ResourceController trait.
 *
 * @package CatLab\Charon\Laravel\Controllers
 */
trait CrudController
{
    /*
     * Required methods
     */
    abstract function getContext($action = Action::VIEW, $parameters = []) : \CatLab\Charon\Interfaces\Context;
    abstract function getResourceDefinition(): ResourceDefinition;

    abstract function getModels($queryBuilder, Context $context, $resourceDefinition = null, $records = null);

    abstract function bodyToResource(Context $context, $resourceDefinition = null) : RESTResource;
    abstract function bodyToResources(Context $context, $resourceDefinition = null) : ResourceCollection;

    abstract function getValidationErrorResponse(ResourceValidationException $e);
    abstract function notFound($id, $resource);
    abstract function toEntity(RESTResource $resource, Context $context, $existingEntity = null, $resourceDefinition = null, $entityFactory = null);

    abstract function toResources($entities, Context $context, $resourceDefinition = null) : ResourceCollection;
    abstract function toResource($entity, Context $context, $resourceDefinition = null) : RESTResource;

    use AuthorizesRequests {
        authorize as laravelAuthorize;
    }

    /**
     * @var Request
     */
    protected $request;

    /**
     * OrganisationController constructor.
     */
    public function __construct()
    {
        if (!defined('static::RESOURCE_DEFINITION')) {
            throw new ResourceException("All classes using CrudController must define a constant called RESOURCE_DEFINITION");
        }

        parent::__construct(static::RESOURCE_DEFINITION);
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->request = $request;

        $this->authorizeIndex($request);
        $context = $this->getContext(Action::INDEX);

        $models = $this->getModels($this->getIndexQuery($request), $context);
        $resources = $this->toResources($models, $context);

        return new ResourceResponse($resources, $context);
    }

    /**
     * View an entity
     * @param Request $request
     * @return Response
     */
    public function view(Request $request)
    {
        $this->request = $request;

        $entity = $this->findEntity($request);
        $this->authorizeView($request, $entity);

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

    /**
     * Create a new entity
     * @return Response
     */
    public function store(Request $request)
    {
        $this->request = $request;

        $this->authorizeCreate($request);

        $writeContext = $this->getContext(Action::CREATE);
        $inputResource = $this->bodyToResource($writeContext);

        try {
            $inputResource->validate($writeContext);
        } catch (ResourceValidationException $e) {
            return $this->getValidationErrorResponse($e);
        }

        $entity = $this->toEntity($inputResource, $writeContext);

        // Save the entity
        $this->saveEntity($request, $entity);

        // Turn back into a resource
        return $this->createViewEntityResponse($entity);
    }

    /**
     * @param Request $request
     * @return ResourceResponse
     * @throws EntityNotFoundException
     */
    public function edit(Request $request)
    {
        $this->request = $request;

        $entity = $this->findEntity($request);
        if (!$entity) {
            throw new EntityNotFoundException('Could not find entity with id ' . $entity->id);
        }

        $this->authorizeEdit($request, $entity);

        $writeContext = $this->getContext(Action::EDIT);
        $inputResource = $this->bodyToResource($writeContext);

        try {
            $inputResource->validate($writeContext, $entity);
        } catch (ResourceValidationException $e) {
            return $this->getValidationErrorResponse($e);
        }

        $entity = $this->toEntity($inputResource, $writeContext, $entity);

        // Save the entity
        if ($entity instanceof Model) {
            $entity->saveRecursively();
        } else {
            $entity->save();
        }

        // Turn back into a resource
        return $this->createViewEntityResponse($entity);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $this->request = $request;

        $entity = $this->findEntity($request);
        $this->authorizeDestroy($request, $entity);

        $entity->delete();

        return $this->toResponse([
            'success' => true,
            'message' => 'Successfully deleted entity.'
        ]);
    }

    /**
     *
     * @param $entity
     * @return ResourceResponse
     */
    protected function createViewEntityResponse($entity)
    {
        $readContext = $this->getContext(Action::VIEW);
        $resource = $this->toResource($entity, $readContext);

        return new ResourceResponse($resource, $readContext);
    }

    /**
     * @return string
     */
    protected function getEntityClassName()
    {
        return $this->getResourceDefinition()->getEntityClassName();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function getIndexQuery(Request $request)
    {
        return $this->callEntityMethod($request, 'query');
    }

    /**
     * Call a static method on the entity.
     * @param Request $request
     * @param $method
     * @return mixed
     */
    protected function callEntityMethod(Request $request, $method)
    {
        // We don't want to include the first argument.
        $args = func_get_args();
        array_shift($args);
        array_shift($args);

        return call_user_func_array([ $this->getEntityClassName(), $method ], $args);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function findEntity(Request $request)
    {
        $id = $request->route()->parameter($this->getIdParameter());

        $entity = $this->callEntityMethod($request, 'find', $id);

        if (!$entity) {
            $this->notFound($id, $this->getEntityClassName());
        }

        return $entity;
    }

    /**
     * @return string
     */
    protected function getIdParameter()
    {
        if (defined('static::RESOURCE_ID')) {
            return static::RESOURCE_ID;
        } else {
            return 'id';
        }
    }

    /**
     * @return Request
     */
    protected function getRequest()
    {
        if (isset($this->request)) {
            return $this->request;
        }

        if (method_exists(\Illuminate\Http\Request::class, 'instance')) {
            return \Request::instance();
        } else {
            return \Request::getInstance();
        }
    }

    /**
     * @param Request $request
     * @param \Illuminate\Database\Eloquent\Model $entity
     */
    protected function saveEntity(Request $request, \Illuminate\Database\Eloquent\Model $entity)
    {
        $isNew = !$entity->exists;

        $this->beforeSaveEntity($request, $entity, $isNew);

        if ($entity instanceof Model) {
            $entity->saveRecursively();
        } else {
            $entity->save();
        }

        $this->afterSaveEntity($request, $entity, $isNew);
    }

    /**
     * Called before saveEntity
     * @param Request $request
     * @param \Illuminate\Database\Eloquent\Model $entity
     * @param bool $isNew
     */
    protected function beforeSaveEntity(Request $request, \Illuminate\Database\Eloquent\Model $entity, $isNew = false)
    {

    }

    /**
     * Called after saveEntity
     * @param Request $request
     * @param \Illuminate\Database\Eloquent\Model $entity
     * @param bool $isNew
     */
    protected function afterSaveEntity(Request $request, \Illuminate\Database\Eloquent\Model $entity, $isNew = false)
    {

    }

    /**
     * Checks if user is authorized to watch an index of the entities.
     * @param Request $request
     */
    protected function authorizeIndex(Request $request)
    {
        $this->authorizeCrudRequest(Action::INDEX);
    }

    /**
     * Checks if user is authorized to create an entity.
     * @param Request $request
     */
    protected function authorizeCreate(Request $request)
    {
        $this->authorizeCrudRequest(Action::CREATE);
    }

    /**
     * Checks if user is authorized to view an entity.
     * @param Request $request
     * @param $entity
     */
    protected function authorizeView(Request $request, $entity)
    {
        $this->authorizeCrudRequest(Action::VIEW, $entity);
    }

    /**
     * Checks if user is authorized to edit the entity.
     * @param Request $request
     * @param $entity
     */
    protected function authorizeEdit(Request $request, $entity)
    {
        $this->authorizeCrudRequest(Action::EDIT, $entity);
    }

    /**
     * Checks if user is authorized to destroy the entity.
     * @param Request $request
     * @param $entity
     */
    protected function authorizeDestroy(Request $request, $entity)
    {
        $this->authorizeCrudRequest(Action::DESTROY, $entity);
    }

    /**
     * @param $action
     * @param null $entity
     * @param null $subject
     */
    protected function authorizeCrudRequest($action, $entity = null, $subject = null)
    {
        if ($entity === null) {
            $entity = $this->getEntityClassName();
        }

        $this->authorize($action, [ $entity, $subject ]);
    }
}


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */
namespace WellCommerce\Bundle\MediaBundle\DataGrid;

use WellCommerce\Bundle\CoreBundle\DataGrid\AbstractDataGrid;
use WellCommerce\Component\DataGrid\Column\Column;
use WellCommerce\Component\DataGrid\Column\ColumnCollection;
use WellCommerce\Component\DataGrid\Column\Options\Appearance;
use WellCommerce\Component\DataGrid\Column\Options\Filter;
use WellCommerce\Component\DataGrid\Column\Options\Sorting;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\DeleteRowEventHandler;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\LoadedEventHandler;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\LoadEventHandler;
use WellCommerce\Component\DataGrid\Configuration\EventHandler\ProcessEventHandler;
use WellCommerce\Component\DataGrid\DataGridInterface;
use WellCommerce\Component\DataGrid\Options\OptionsInterface;

/**
 * Class MediaDataGrid
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class MediaDataGrid extends AbstractDataGrid
{
    /**
     * {@inheritdoc}
     */
    public function configureColumns(ColumnCollection $collection)
    {
        $collection->add(new Column([
            'id'         => 'id',
            'caption'    => $this->trans('common.label.id'),
            'sorting'    => new Sorting([
                'default_order' => Sorting::SORT_DIR_DESC,
            ]),
            'appearance' => new Appearance([
                'visible' => false,
            ]),
            'filter'     => new Filter([
                'type' => Filter ::FILTER_BETWEEN,
            ]),
        ]));

        $collection->add(new Column([
            'id'         => 'preview',
            'caption'    => $this->trans('common.label.preview'),
            'appearance' => new Appearance([
                'width' => 30,
                'align' => Appearance::ALIGN_CENTER,
            ]),
        ]));

        $collection->add(new Column([
            'id'      => 'name',
            'caption' => $this->trans('common.label.name'),
        ]));

        $collection->add(new Column([
            'id'      => 'mime',
            'caption' => $this->trans('common.label.mime'),
        ]));

        $collection->add(new Column([
            'id'      => 'extension',
            'caption' => $this->trans('common.label.extension'),
        ]));

        $collection->add(new Column([
            'id'      => 'size',
            'caption' => $this->trans('common.label.size'),
        ]));
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsInterface $options)
    {
        $eventHandlers = $options->getEventHandlers();

        $eventHandlers->add(new LoadEventHandler([
            'function' => $this->getJavascriptFunctionName('load'),
            'route'    => $this->getActionUrl('grid'),
        ]));

        $eventHandlers->add(new DeleteRowEventHandler([
            'function'   => $this->getJavascriptFunctionName('delete'),
            'row_action' => DataGridInterface::ACTION_DELETE,
            'route'      => $this->getActionUrl('delete'),
        ]));

        $eventHandlers = $options->getEventHandlers();

        $eventHandlers->add(new ProcessEventHandler([
            'function' => $this->getJavascriptFunctionName('process'),
        ]));

        $eventHandlers->add(new LoadedEventHandler([
            'function' => $this->getJavascriptFunctionName('data_loaded'),
        ]));
    }
}


<?php

/**
 * MIT License
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Spryker\Zed\SalesOrderThresholdDataImport;

use Spryker\Zed\DataImport\DataImportDependencyProvider;
use Spryker\Zed\Kernel\Container;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToCurrencyFacadeBridge;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToSalesOrderThresholdFacadeBridge;
use Spryker\Zed\SalesOrderThresholdDataImport\Dependency\Facade\SalesOrderThresholdDataImportToStoreFacadeBridge;

/**
 * @method \Spryker\Zed\SalesOrderThresholdDataImport\SalesOrderThresholdDataImportConfig getConfig()
 */
class SalesOrderThresholdDataImportDependencyProvider extends DataImportDependencyProvider
{
    public const FACADE_SALES_ORDER_THRESHOLD = 'FACADE_SALES_ORDER_THRESHOLD';
    public const FACADE_STORE = 'FACADE_STORE';
    public const FACADE_CURRENCY = 'FACADE_CURRENCY';

    /**
     * @param \Spryker\Zed\Kernel\Container $container
     *
     * @return \Spryker\Zed\Kernel\Container
     */
    public function provideBusinessLayerDependencies(Container $container): Container
    {
        $container = parent::provideBusinessLayerDependencies($container);

        $container = $this->addSalesOrderThresholdFacade($container);
        $container = $this->addStoreFacade($container);
        $container = $this->addCurrencyFacade($container);

        return $container;
    }

    /**
     * @param \Spryker\Zed\Kernel\Container $container
     *
     * @return \Spryker\Zed\Kernel\Container
     */
    protected function addSalesOrderThresholdFacade(Container $container): Container
    {
        $container[static::FACADE_SALES_ORDER_THRESHOLD] = function (Container $container) {
            return new SalesOrderThresholdDataImportToSalesOrderThresholdFacadeBridge(
                $container->getLocator()->salesOrderThreshold()->facade()
            );
        };

        return $container;
    }

    /**
     * @param \Spryker\Zed\Kernel\Container $container
     *
     * @return \Spryker\Zed\Kernel\Container
     */
    protected function addStoreFacade(Container $container): Container
    {
        $container[static::FACADE_STORE] = function (Container $container) {
            return new SalesOrderThresholdDataImportToStoreFacadeBridge(
                $container->getLocator()->store()->facade()
            );
        };

        return $container;
    }

    /**
     * @param \Spryker\Zed\Kernel\Container $container
     *
     * @return \Spryker\Zed\Kernel\Container
     */
    protected function addCurrencyFacade(Container $container): Container
    {
        $container[static::FACADE_CURRENCY] = function (Container $container) {
            return new SalesOrderThresholdDataImportToCurrencyFacadeBridge(
                $container->getLocator()->currency()->facade()
            );
        };

        return $container;
    }
}


<?php

namespace Environaut;

use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Environaut\Command;

/**
 * The console application that handles all
 * supported command line arguments.
 */
class Application extends BaseApplication
{
    public function __construct($version)
    {
        parent::__construct('Environaut', $version);
    }

    /**
     * {@inheritDoc}
     */
    public function doRun(InputInterface $input, OutputInterface $output)
    {
        if ($input->hasParameterOption('--profile')) {
            $start_time = microtime(true);
        }

        $result = parent::doRun($input, $output);

        if (isset($start_time)) {
            $output->writeln(
                PHP_EOL . '<comment>Memory usage: ' . round(memory_get_usage() / 1024 / 1024, 2) .
                'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) .
                'MB), time: ' . round(microtime(true) - $start_time, 2) . 's</comment>' . PHP_EOL
            );
        }

        return $result;
    }

    /**
     * Initializes all necessary commands
     */
    protected function getDefaultCommands()
    {
        $commands = parent::getDefaultCommands();

        $commands[] = new Command\AboutCommand();
        $commands[] = new Command\CheckCommand();

        return $commands;
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultInputDefinition()
    {
        $definition = parent::getDefaultInputDefinition();

        $definition->addOption(
            new InputOption(
                'profile',
                null,
                InputOption::VALUE_NONE,
                'Display timing and memory usage information.'
            )
        );

        return $definition;
    }
}


<?php

namespace InetStudio\Access\Services\Back;

use InetStudio\Access\Contracts\Services\Back\AccessServiceContract;

/**
 * Class AccessService.
 */
class AccessService implements AccessServiceContract
{
    /**
     * Присваиваем доступы объекту.
     *
     * @param $request
     *
     * @param $item
     */
    public function attachToObject($request, $item)
    {
        if ($request->filled('access')) {
            $item->removeAccess();

            foreach ($request->get('access') as $field => $access) {
                $item->addAccess($field, $access);
            }
        } else {
            $item->removeAccess();
        }
    }
}


<?php

namespace Ekyna\Bundle\SitemapBundle\Provider;

/**
 * Class ProviderRegistry
 * @package Ekyna\Bundle\SitemapBundle\Provider
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ProviderRegistry implements ProviderRegistryInterface
{
    /**
     * @var array|ProviderInterface[]
     */
    private $providers;

    /**
     * @var array
     */
    private $sitemaps;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->providers = [];
        $this->sitemaps = [];
    }

    /**
     * {@inheritdoc}
     */
    public function addProvider(ProviderInterface $provider)
    {
        if (array_key_exists($provider->getName(), $this->providers)) {
            throw new \InvalidArgumentException(sprintf('Provider "%s" is already registered.', $provider->getName()));
        }
        if (!in_array($provider->getSitemap(), $this->sitemaps)) {
            $this->sitemaps[] = $provider->getSitemap();
        }
        $this->providers[$provider->getName()] = $provider;
    }

    /**
     * {@inheritdoc}
     */
    public function getProvidersBySitemap($sitemap)
    {
        $providers = [];
        foreach($this->providers as $provider) {
            if ($provider->getSitemap() === $sitemap) {
                $providers[] = $provider;
            }
        }
        return $providers;
    }

    /**
     * {@inheritdoc}
     */
    public function getProviders()
    {
        return $this->providers;
    }

    /**
     * {@inheritdoc}
     */
    public function getSitemaps()
    {
        return $this->sitemaps;
    }
}


<?php
/**
 * OAuth 2.0 Refresh token entity
 *
 */

namespace OAuth2\Server\Entity;

/**
 * Refresh token entity class
 */
class RefreshTokenEntity extends AbstractTokenEntity
{
    /**
     * Access token associated to refresh token
     *
     * @var \OAuth2\Server\Entity\AccessTokenEntity
     */
    protected $accessTokenEntity;

    /**
     * Id of the access token
     *
     * @var string
     */
    protected $accessTokenId;

    /**
     * Set the ID of the associated access token
     *
     * @param string $accessTokenId
     *
     * @return self
     */
    public function setAccessTokenId($accessTokenId)
    {
        $this->accessTokenId = $accessTokenId;

        return $this;
    }

    /**
     * Associate an access token
     *
     * @param \OAuth2\Server\Entity\AccessTokenEntity $accessTokenEntity
     *
     * @return self
     */
    public function setAccessToken(AccessTokenEntity $accessTokenEntity)
    {
        $this->accessTokenEntity = $accessTokenEntity;

        return $this;
    }

    /**
     * Return access token
     *
     * @return AccessTokenEntity
     */
    public function getAccessToken()
    {
        if (! $this->accessTokenEntity instanceof AccessTokenEntity) {
            $this->accessTokenEntity = $this->server->getAccessTokenStorage()->get($this->accessTokenId);
        }

        return $this->accessTokenEntity;
    }

    /**
     * {@inheritdoc}
     */
    public function save()
    {
		if ($this->isNew) {
			$this->server->getRefreshTokenStorage()->create(
				$this->getId(),
				$this->getExpireTime(),
				$this->getAccessToken()->getId()
			);
		}else{
			$this->server->getRefreshTokenStorage()->save($this);
		}
    }

    /**
     * {@inheritdoc}
     */
    public function expire()
    {
        $this->server->getRefreshTokenStorage()->delete($this);
    }
}


<?php
/**
 * User  : Nikita Makarov
 * Date  : 1/5/16
 * E-Mail: mesaverde228@gmail.com
 *
 * @file
 * Description
 */

namespace Akuma\Bundle\UserBundle\Doctrine;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use FOS\UserBundle\Model\UserInterface;

class UserManager extends \FOS\UserBundle\Doctrine\UserManager
{
    /**
     * Updates a user.
     *
     * @param UserInterface $user
     * @param Boolean       $andFlush Whether to flush the changes (default true)
     */
    public function updateUser(UserInterface $user, $andFlush = true)
    {
        /** @var EntityManager $em */
        $em = $this->objectManager;
        $meta = $em->getClassMetadata(get_class($user));
        $roleClass = $meta->getAssociationTargetClass('roles');
        $roles = array();
        foreach ($user->getRoles() as $role) {
            if ($roleClass !== get_class($role)) {
                /** Try to get Role */
                if ($em->find($roleClass, $role->getRole())) {
                    try {
                        $_ref = $em->getReference($roleClass, $role->getRole());
                        $roles[] = $_ref;
                    } catch (ORMException $e) {
                        var_dump($e);
                    }
                }else{
                    $_ref = new $roleClass($role->getRole());
                    $em->persist($_ref);
                    $roles[] = $_ref;
                }
            }else{
                $roles[] = $role;
            }
        }
        $user->setRoles($roles);
        parent::updateUser($user, $andFlush);
    }
}


<?php
namespace T3v\T3vContent\Service;

use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;

use T3v\T3vCore\Service\AbstractService;

/**
 * The extension service class.
 *
 * @package T3v\T3vContent\Service
 */
class ExtensionService extends AbstractService {
  /**
   * The modes which T3v Content supports.
   */
  const STRICT_MODE   = 'strict';
  const FALLBACK_MODE = 'fallback';

  /**
   * Checks if T3v Content is running in `strict` mode.
   *
   * @return bool If T3v Content is running in `strict` mode
   */
  public function runningInStrictMode(): bool {
    $strictMode = true;
    $settings   = $this->getSettings();

    if (is_array($settings) && !empty($settings)) {
      $mode = $settings['mode'];

      if ($mode != self::STRICT_MODE) {
        $strictMode = false;
      }
    }

    return $strictMode;
  }

  /**
   * Checks if T3v Content is running in `fallback` mode.
   *
   * @return bool If T3v Content is running in `fallback` mode
   */
  public function runningInFallbackMode(): bool {
    $fallbackMode = false;
    $settings     = $this->getSettings();

    if (is_array($settings) && !empty($settings)) {
      $mode = $settings['mode'];

      if ($mode === self::FALLBACK_MODE) {
        $fallbackMode = true;
      }
    }

    return $fallbackMode;
  }

  /**
   * Gets the settings from `plugin.tx_t3vcontent.settings`.
   *
   * @return array The settings
   */
  protected function getSettings(): array {
    $configurationManager = $this->objectManager->get(ConfigurationManagerInterface::class);
    $configuration        = $configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);

    return $configuration['plugin.']['tx_t3vcontent.']['settings.'];
  }
}


<?php

namespace UWDOEM\Group;

use UWDOEM\Connection\Connection;
use Sunra\PhpSimple\HtmlDomParser;

/**
 * Container class for data received from Group Web Service and Student Web Service
 *
 * @package UWDOEM\Group
 */
class Group
{
    /** @var string */
    protected $identifier;

    /** @var string|null */
    protected $regid = null;
    /** @var array */
    protected $names = [];
    /** @var string */
    protected $title;
    /** @var string */
    protected $description;
    /** @var string */
    protected $contact;
    /** @var string */
    protected $createtime;
    /** @var string */
    protected $modifytime;
    /** @var string */
    protected $membermodifytime;

    /** @var string */
    protected $authnfactor;
    /** @var string */
    protected $classification;
    /** @var string */
    protected $dependson;
    /** @var string */
    protected $gid;

    /** @var string */
    protected $emailenabled;
    /** @var string */
    protected $publishemail;
    /** @var array */
    protected $authorigs = [];
    /** @var boolean */
    protected $reporttoorig = false;

    /** @var array */
    protected $admins = [];
    /** @var array */
    protected $updaters = [];
    /** @var array */
    protected $creators = [];
    /** @var array */
    protected $readers = [];
    /** @var array */
    protected $viewers = [];
    /** @var array */
    protected $optins = [];
    /** @var array */
    protected $optouts = [];
    /** @var string */
    protected $owners;

    /** @var array */
    protected $history = [];

    // if a group represents a course, course information is included in the group info
    /** @var string */
    protected $course_qtr;
    /** @var string */
    protected $course_year;
    /** @var string */
    protected $course_curr;
    /** @var string */
    protected $course_no;
    /** @var string */
    protected $course_sect;
    /** @var string */
    protected $course_sln;
    /** @var array */
    protected $course_instructors = [];

    /** @var array */
    protected $directmembers = [];
    /** @var array */
    protected $effectivemembers = [];

    /**
     * @return string
     */
    public function getRegid()
    {
        if (isset($this->regid) === false) {
            $this->getGroup();
        }
        return $this->regid;
    }

    /**
     * @return array
     */
    public function getNames()
    {
        if (isset($this->names) === false) {
            $this->getGroup();
        }
        return $this->names;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        if (isset($this->title) === false) {
            $this->getGroup();
        }
        return $this->title;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        if (isset($this->description) === false) {
            $this->getGroup();
        }
        return $this->description;
    }

    /**
     * @return string
     */
    public function getContact()
    {
        if (isset($this->contact) === false) {
            $this->getGroup();
        }
        return $this->contact;
    }

    /**
     * @return string
     */
    public function getCreatetime()
    {
        if (isset($this->createtime) === false) {
            $this->getGroup();
        }
        return $this->createtime;
    }

    /**
     * @return string
     */
    public function getModifytime()
    {
        if (isset($this->modifytime) === false) {
            $this->getGroup();
        }
        return $this->modifytime;
    }

    /**
     * @return string
     */
    public function getMembermodifytime()
    {
        if (isset($this->membermodifytime) === false) {
            $this->getGroup();
        }
        return $this->membermodifytime;
    }

    /**
     * @return string
     */
    public function getAuthnfactor()
    {
        if (isset($this->authnfactor) === false) {
            $this->getGroup();
        }
        return $this->authnfactor;
    }

    /**
     * @return string
     */
    public function getClassification()
    {
        if (isset($this->classification) === false) {
            $this->getGroup();
        }
        return $this->classification;
    }

    /**
     * @return string
     */
    public function getDependson()
    {
        if (isset($this->dependson) === false) {
            $this->getGroup();
        }
        return $this->dependson;
    }
    /**
     * @return string
     */
    public function getGid()
    {
        if (isset($this->gid) === false) {
            $this->getGroup();
        }
        return $this->gid;
    }

    /**
     * @return string
     */
    public function getEmailenabled()
    {
        if (isset($this->emailenabled) === false) {
            $this->getGroup();
        }
        return $this->emailenabled;
    }

    /**
     * @return string
     */
    public function getPublishemail()
    {
        if (isset($this->publishemail) === false) {
            $this->getGroup();
        }
        return $this->publishemail;
    }

    /**
     * @return string
     */
    public function getAuthorigs()
    {
        if (isset($this->authorigs) === false) {
            $this->getGroup();
        }
        return $this->authorigs;
    }

    /**
     * @return array
     */
    public function getReporttoorig()
    {
        if (isset($this->reporttoorig) === false) {
            $this->getGroup();
        }
        return $this->reporttoorig;
    }

    /**
     * @return array
     */
    public function getAdmins()
    {
        if (isset($this->admins) === false) {
            $this->getGroup();
        }
        return $this->admins;
    }

    /**
     * @return array
     */
    public function getUpdaters()
    {
        if (isset($this->updaters) === false) {
            $this->getGroup();
        }
        return $this->updaters;
    }

    /**
     * @return array
     */
    public function getCreators()
    {
        if (isset($this->creators) === false) {
            $this->getGroup();
        }
        return $this->creators;
    }

    /**
     * @return array
     */
    public function getReaders()
    {
        if (isset($this->readers) === false) {
            $this->getGroup();
        }
        return $this->readers;
    }

    /**
     * @return array
     */
    public function getViewers()
    {
        if (isset($this->viewers) === false) {
            $this->getGroup();
        }
        return $this->viewers;
    }

    /**
     * @return array
     */
    public function getOptins()
    {
        if (isset($this->optins) === false) {
            $this->getGroup();
        }
        return $this->optins;
    }

    /**
     * @return array
     */
    public function getOptouts()
    {
        if (isset($this->optouts) === false) {
            $this->getGroup();
        }
        return $this->optouts;
    }

    /**
     * @return array
     */
    public function getMembers()
    {
        if (isset($this->members) === false) {
            $this->getDirectMembership();
            $this->getEffectiveMembership();
        }
        return array_merge($this->directmembers, $this->effectivemembers);
    }

    /**
     * @return array
     */
    public function getOwners()
    {
        if (isset($this->owners) === false) {
            $this->getGroup();
        }
        return $this->owners;
    }

    /**
     * @return string
     */
    public function getCourseQtr()
    {
        if (isset($this->course_qtr) === false) {
            $this->getGroup();
        }
        return $this->course_qtr;
    }

    /**
     * @return string
     */
    public function getCourseYear()
    {
        if (isset($this->course_year) === false) {
            $this->getGroup();
        }
        return $this->course_year;
    }

    /**
     * @return string
     */
    public function getCourseCurr()
    {
        if (isset($this->course_curr) === false) {
            $this->getGroup();
        }
        return $this->course_curr;
    }

    /**
     * @return string
     */
    public function getCourseNo()
    {
        if (isset($this->course_no) === false) {
            $this->getGroup();
        }
        return $this->course_no;
    }

    /**
     * @return string
     */
    public function getCourseSect()
    {
        if (isset($this->course_sect) === false) {
            $this->getGroup();
        }
        return $this->course_sect;
    }

    /**
     * @return string
     */
    public function getCourseSln()
    {
        if (isset($this->course_sln) === false) {
            $this->getGroup();
        }
        return $this->course_sln;
    }

    /**
     * @return array
     */
    public function getCourseInstructors()
    {
        if (isset($this->course_instructors) === false) {
            $this->getGroup();
        }
        return $this->course_instructors;
    }

    /**
     * @return array
     */
    public function getDirectmembers()
    {
        if (isset($this->directmembers) === false) {
            $this->getDirectMembership();
        }
        return $this->directmembers;
    }

    /**
     * @return array
     */
    public function getEffectivemembers()
    {
        if (isset($this->effectivemembers) === false) {
            $this->getEffectiveMembership();
        }
        return $this->effectivemembers;
    }

    /**
     * @return array
     */
    public function getHistory()
    {
        if (count($this->history) === 0) {
            $this->getGroupHistory();
        }
        return $this->history;
    }

    /** @var \UWDOEM\Connection\Connection */
    protected static $groupConnection;

    /**
     * Group constructor.
     * @param string $identifier
     */
    public function __construct($identifier)
    {
        $this->identifier = $identifier;
        return $this;
    }

    /**
     * Queries GWS to generate a Group, given an identifier. Identifier may be group id, or group regid
     *
     * @return Group
     */
    public function getGroup()
    {
        /** @var null|Person $person */

        if (is_null($this->regid) === true) {
            try {
                $resp = static::getGroupConnection()->execGET(
                    $this->identifier
                );
            } catch (\Exception $e) {
                throw $e;
            }

            $this->parseGroup($resp->getData());
        }

        return $this;
    }

    /**
     * Queries GWS to for groups. Search parameters are defined at
     * https://wiki.cac.washington.edu/display/infra/Groups+WebService+Search
     *
     * @param string $search_string E.G. "name=thing_one&stem=thing_two".
     * @return array
     */
    public function searchGroups($search_string)
    {
        $resp = static::makeConnection('')->execGET(
            "search/?$search_string"
        );
        return $this->parseSearch($resp->getData());
    }

    /**
     * @param string $member_id E.G. 'bonifacp'.
     * @return string
     */
    public function getMember($member_id)
    {

        if (is_null($this->regid) === true) {
            throw new \Exception('Member Id not specified');
        } else {
            $resp = static::getGroupConnection()->execGET(
                "$this->identifier/member/$member_id"
            );

            return $this->parseMember($resp->getData());
        }
    }

    /**
     * @param string $member_id E.G. 'bonifacp'.
     * @return string
     */
    public function getEffectiveMember($member_id)
    {
        if (is_null($this->regid) === true) {
            throw new \Exception('Member Id not specified');
        } else {
            $resp = static::makeConnection()->execGET(
                "$this->identifier/effective_member/$member_id"
            );

            return $resp;
        }
    }

    /**
     * @param string $affiliate_id May be identifier (uw_enrollment) or regid (3ff762ad88924cdd80d5b376c4ba3e1d).
     * @return array
     */
    public function getAffiliate($affiliate_id)
    {
        $resp = static::getGroupConnection()->execGET(
            "$this->identifier/affiliate/$affiliate_id"
        );

        return $this->parseAffiliate($resp->getData());
    }

    /**
     * Queries GWS to get the groups history.
     * @return void
     */
    public function getGroupHistory()
    {
        $resp = static::getGroupConnection()->execGET(
            "$this->identifier/history"
        );

        $this->parseHistory($resp->getData());
    }

    /**
     * Queries GWS to for direct members of the group. Members are added to the object.
     * @return void
     */
    protected function getDirectMembership()
    {
        if (isset($this->regid) === false) {
            $this->getGroup();
        }
        if (is_null($this->regid) === true) {
            throw new \Exception('Group Id not specified');
        }
        $resp = static::getGroupConnection()->execGET(
            "$this->identifier/member"
        );

        $this->directmembers = [];
        $this->parseMembership($resp->getData());
    }

    /**
     * Queries GWS to for effective members of the group. Members are added to the object.
     * @return void
     */
    protected function getEffectiveMembership()
    {
        if (isset($this->regid) === false) {
            $this->getGroup();
        }
        if (is_null($this->regid) === true) {
            throw new \Exception('Group Id not specified');
        }
        try {
            $resp = static::getGroupConnection()->execGET(
                "$this->identifier/effective_member"
            );
        } catch (\Exception $e) {
            throw $e;
        }

        $this->effectivemembers = [];
        $this->parseMembership($resp->getData());
    }

    /**
     * @param string $baseUrl
     * @return Connection
     * @throws \Exception If any of the required constants have not been set.
     */
    protected static function makeConnection($baseUrl)
    {
        $requiredConstants = [
            "UW_GWS_BASE_PATH",
            "UW_GWS_SSL_KEY_PATH",
            "UW_GWS_SSL_CERT_PATH",
            "UW_GWS_SSL_KEY_PASSWD"
        ];
        foreach ($requiredConstants as $constant) {
            if (defined($constant) === false) {
                throw new \Exception("You must define the constant $constant before using this library.");
            }
        }

        return new Connection(
            UW_GWS_BASE_PATH . $baseUrl,
            UW_GWS_SSL_KEY_PATH,
            UW_GWS_SSL_CERT_PATH,
            UW_GWS_SSL_KEY_PASSWD,
            defined("UW_GWS_VERBOSE") && UW_GWS_VERBOSE
        );
    }

    /**
     * @return Connection
     */
    protected static function getGroupConnection()
    {
        if (static::$groupConnection === null) {
            static::$groupConnection = static::makeConnection("group/");
        }
        return static::$groupConnection;
    }

    /**
     * @param string $data
     * @return void
     */
    protected function parseGroup($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        $this->regid = (is_null($html->find("span.regid", 0)) === false)
                            ? $html->find("span.regid", 0)->innertext
                            : null;

        // Determine if the query returned an actual Group, or en empty object.
        // GWS has some templating issues, where missing data leaves the templating code. So if it's missing the regid,
        // we just skip the rest of the parsing.
        if ($this->regid === '${group.regid}') {
            $this->regid = null;
        } else {
            //Get the basic/core Group data
            $this->title             = (is_null($html->find("span.title           ", 0)) === false)
                                            ? $html->find("span.title           ", 0)->innertext
                                            : null;

            $this->description       = (is_null($html->find("span.description     ", 0)) === false)
                                            ? $html->find("span.description     ", 0)->innertext
                                            : null;

            $this->contact           = (is_null($html->find("span.contact         ", 0)) === false)
                                            ? $html->find("span.contact         ", 0)->innertext
                                            : null;

            $this->createtime        = (is_null($html->find("span.createtime      ", 0)) === false)
                                            ? $html->find("span.createtime      ", 0)->innertext
                                            : null;

            $this->modifytime        = (is_null($html->find("span.modifytime      ", 0)) === false)
                                            ? $html->find("span.modifytime      ", 0)->innertext
                                            : null;

            $this->membermodifytime  = (is_null($html->find("span.membermodifytime", 0)) === false)
                                            ? $html->find("span.membermodifytime", 0)->innertext
                                            : null;

            $this->authnfactor       = (is_null($html->find("span.authnfactor     ", 0)) === false)
                                            ? $html->find("span.authnfactor     ", 0)->innertext
                                            : null;

            $this->classification    = (is_null($html->find("span.classification  ", 0)) === false)
                                            ? $html->find("span.classification  ", 0)->innertext
                                            : null;

            $this->dependson         = (is_null($html->find("span.dependson       ", 0)) === false)
                                            ? $html->find("span.dependson       ", 0)->innertext
                                            : null;

            $this->gid               = (is_null($html->find("span.gid             ", 0)) === false)
                                            ? $html->find("span.gid             ", 0)->innertext
                                            : null;

            $this->emailenabled      = (is_null($html->find("span.emailenabled    ", 0)) === false)
                                            ? $html->find("span.emailenabled    ", 0)->innertext
                                            : null;

            $this->publishemail      = (is_null($html->find("span.publishemail    ", 0)) === false)
                                            ? $html->find("span.publishemail    ", 0)->innertext
                                            : null;

            $this->reporttoorig      = (is_null($html->find("span.reporttoorig    ", 0)) === false)
                                            ? $html->find("span.reporttoorig    ", 0)->innertext
                                            : null;

            $this->status            = (is_null($html->find("div.status           ", 0)) === false)
                                            ? $html->find("div.status           ", 0)->innertext
                                            : null;

            foreach ($html->find('span.name') as $name) {
                array_push($this->names, $name->innertext);
            }
            foreach ($html->find('li.authorig') as $authorig) {
                array_push($this->authorigs, $authorig->innertext);
            }
            foreach ($html->find('li.admin') as $admin) {
                array_push($this->admins, $admin->innertext);
            }
            foreach ($html->find('li.updater') as $updater) {
                array_push($this->updaters, $updater->innertext);
            }
            foreach ($html->find('li.reader') as $reader) {
                array_push($this->readers, $reader->innertext);
            }
            foreach ($html->find('li.optin') as $optin) {
                array_push($this->optins, $optin->innertext);
            }
            foreach ($html->find('li.optout') as $optout) {
                array_push($this->optours, $optout->innertext);
            }

            // Course fields are optional in the GWS XHTML
            foreach ($html->find('li.course_instructor') as $instructor) {
                array_push($this->course_instructors, $instructor->innertext);
            }

            $this->course_qtr  = (is_null($html->find("span.course_qtr", 0)) === false)
                                    ? $html->find("span.course_qtr", 0)->innertext
                                    : null;

            $this->course_year = (is_null($html->find("span.course_year", 0)) === false)
                                    ? $html->find("span.course_year", 0)->innertext
                                    : null;

            $this->course_curr = (is_null($html->find("span.course_curr", 0)) === false)
                                    ? $html->find("span.course_curr", 0)->innertext
                                    : null;

            $this->course_no   = (is_null($html->find("span.course_no", 0)) === false)
                                    ? $html->find("span.course_no", 0)->innertext
                                    : null;

            $this->course_sect = (is_null($html->find("span.course_sect", 0)) === false)
                                    ? $html->find("span.course_sect", 0)->innertext
                                    : null;

            $this->course_sln  = (is_null($html->find("span.course_sln", 0)) === false)
                                    ? $html->find("span.course_sln", 0)->innertext
                                    : null;
        }
    }

    /**
     * parses Membership data and saves it to the Group object
     *
     * @param string $data
     * @return void
     */
    protected function parseMembership($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        foreach ($html->find('a.member') as $name) {
            array_push($this->directmembers, $name->innertext);
        }
        foreach ($html->find('a.effective_member') as $name) {
            array_push($this->effectivemembers, $name->innertext);
        }
    }

    /**
     * parses History data and saves it to the Group object
     *
     * @param string $data
     * @return void
     */
    protected function parseHistory($data)
    {
        $this->history = [];
        $html = HtmlDomParser::str_get_html($data);
        foreach ($html->find('li.history') as $e) {
            $item = array();
            $item['date'] =  $e->date;
            $item['user'] =  $e->user;
            $item['actas'] =  $e->actas;
            $item['activity'] =  $e->activity;
            $item['description'] = $e->description;
            array_push($this->history, $item);
        }
    }

/**
 *      Why? Because it's in the API
 *      Why is it in the API? ¯\_(ツ)_/¯
 * /

    /**
     * parses Member data and returns it
     * @param string $data
     * @return string member name
     */
    protected function parseMember($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        return $html->find('span.member', 0)->innertext;
    }

    /**
     * Parses out affiliate information from the GWS XHTML. Successful queries will also be added to the Group object.
     *
     * @param string $data
     * @return array affiliate information
     */
    protected function parseAffiliate($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        $affiliate['group_identifier']  = (empty($html->find('span.identifier', 0)) === false)
                                            ? ($html->find('span.identifier', 0)->innertext)
                                            : ('');
        $affiliate['affiliate_name']    = (empty($html->find('span.affiliate', 0)) === false)
                                            ? ($html->find('span.affiliate', 0)->name)
                                            : ('');
        $affiliate['affiliate_status']  = (empty($html->find('span.affiliate', 0)) === false)
                                            ? ($html->find('span.affiliate', 0)->status)
                                            : ('');
        $affiliate['error']             = (empty($html->find('span.error', 0)) === false)
                                            ? ($html->find('span.error', 0)->innertext)
                                            : ('');

        if ($html->find('span.error', 0) === true) {
        } else {
            $this->affiliates[$affiliate['affiliate_name']] = $affiliate;
        }

        return $affiliate;
    }

    /**
     * Parses out group information from a search.
     *
     * @param string $data
     * @return array group information
     */
    protected function parseSearch($data)
    {
        $html = HtmlDomParser::str_get_html($data);
        $groups = array();
        foreach ($html->find('li.groupreference') as $e) {
            $item = array();
            $item['regid'] =  $e->find('span.regid', 0)->innertext;
            $item['title'] =  $e->find('span.title', 0)->innertext;
            $item['description'] = $e->find('span.description', 0)->innertext;
            array_push($groups, $item);
        }
        return $groups;
    }
}


<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: LabelList.php 543 2009-10-03 08:50:00Z mr_a_ton$
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\LabelText;

/**
 * LebelText - class LabelText is element that view value who binds
 * with a BizField
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2009
 * @version 1.0
 * @access public
 */
class LabelTextarea extends LabelText
{
    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
       $value = $this->text ? $this->getText() : $this->value;

        if ($value == null || $value =="")
            return "";

        $style = $this->getStyle();
        $id = $this->objectName;
        $func = $this->getFunction();

        if ($this->translatable == 'Y')
            $value = $this->translateString($value);

        if((int)$this->maxLength>0){
	        if(function_exists('mb_strlen') && function_exists('mb_substr')){
	        	if(mb_strlen($value,'UTF8') > (int)$this->maxLength){
	        		$value = mb_substr($value,0,(int)$this->maxLength,'UTF8').'...';
	        	}
	        }else{
	        	if(strlen($value) > (int)$this->maxLength){
	        		$value = substr($value,0,(int)$this->maxLength).'...';
	        	}
	        }
        }
        /*
         * it is important converting not just nl2br
         *
         */

        //$value = htmlentities($value);

        $value = htmlentities($value, ENT_QUOTES, "UTF-8");
        $value = str_replace("\n\n","\ngetImageUrl()."/spacer.gif\" style=\"display:block;height:10px;\">",$value);
        $value = nl2br($value);

        if ($value!=null)
        {
        	if($this->displayFormat)
        	{
        		$value = sprintf($this->displayFormat,$value);
        	}
        	if($this->percent=='Y')
        	{
        		$value = sprintf("%.2f",$value*100).'%';
        	}

            if ($this->link)
            {
                $link = $this->getLink();
                $target = $this->getTarget();
                //$sHTML = "" . $val . "";
                $sHTML = "" . $value . "";
            }
            else
            {
                $sHTML = "" . $value . "";
            }
        }

        return $sHTML;    }

}


<?php
/**
 * Annotations
 *
 * @package     Chrisguitarguy\Annotation
 * @copyright   Christopher Davis <http://christopherdavis.me>
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\Annotation;

/**
 * The default annotation context.
 *
 * @since   0.1
 * @author  Christopher Davis <http://christopherdavis.me>
 */
class AnnotationContext implements AnnotationContextInterface
{
    /**
     * The context array from the reader.
     *
     * @since   0.1
     * @access  protected
     * @var     array
     */
    protected $context = array();

    /**
     * Constructor. Set up the context.
     *
     * @since   0.1
     * @access  public
     * @param   array $context
     * @return  void
     */
    public function __construct(array $context)
    {
        $this->context = $context;
    }

    /**
     * {@inheritdoc}
     */
    public function hasContext($ctx)
    {
        $cur = $this->getContext();
        return ($cur & $ctx) === $cur;
    }

    /**
     * {@inheritdoc}
     */
    public function getContext()
    {
        if (isset($this->context['function'])) {
            return AnnotationContextInterface::IS_FUNCTION;
        } elseif (isset($this->context['method'])) {
            return AnnotationContextInterface::IS_METHOD;
        } elseif (isset($this->context['property'])) {
            return AnnotationContextInterface::IS_PROPERTY;
        } else {
            return AnnotationContextInterface::IS_CLASS;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getClass()
    {
        if (isset($this->context['class'])) {
            return $this->context['class'];
        }

        $cls = null;
        if (isset($this->context['property'])) {
            $cls = $this->context['property']->getDeclaringClass();
        } elseif (isset($this->context['method'])) {
            $cls = $this->context['method']->getDeclaringClass();
        }

        if ($cls) {
            return $this->context['class'] = $cls;
        }

        throw new \BadMethodCallException(sprintf('%s called from a function context', __METHOD__));
    }

    /**
     * {@inheritdoc}
     */
    public function getMethod()
    {
        if (isset($this->context['method'])) {
            return $this->context['method'];
        }

        throw new \BadMethodCallException(sprintf('%s called from a non-method context', __METHOD__));
    }

    /**
     * {@inheritdoc}
     */
    public function getProperty()
    {
        if (isset($this->context['property'])) {
            return $this->context['property'];
        }

        throw new \BadMethodCallException(sprintf('%s called from a non-property context', __METHOD__));
    }

    /**
     * {@inheritdoc}
     */
    public function getFunction()
    {
        if (isset($this->context['function'])) {
            return $this->context['function'];
        }

        throw new \BadMethodCallException(sprintf('%s called from a non-function context', __METHOD__));
    }
}