<commit_before><?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2013 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\Apigility\Doctrine\Admin\Model;

use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\Filter\FilterChain;
use Zend\View\Model\ViewModel;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use ZF\Apigility\Admin\Exception;
use ZF\Configuration\ConfigResource;
use ZF\Configuration\ModuleUtils;
use ZF\Rest\Exception\CreationException;
use Zf\Apigility\Admin\Model\ModuleEntity;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use ZF\ApiProblem\ApiProblem;

class DoctrineRestServiceModel implements EventManagerAwareInterface, ServiceManagerAwareInterface
{
    /**
     * @var ConfigResource
     */
    protected $configResource;

    /**
     * @var EventManagerInterface
     */
    protected $events;

    /**
     * @var string
     */
    protected $module;

    /**
     * @var ModuleEntity
     */
    protected $moduleEntity;

    /**
     * @var string
     */
    protected $modulePath;

    /**
     * @var ModuleUtils
     */
    protected $modules;

    /**
     * @var PhpRenderer
     */
    protected $renderer;

    /**
     * Allowed REST update options that are scalars
     *
     * @var array
     */
    protected $restScalarUpdateOptions = array(
        'pageSize'                 => 'page_size',
        'pageSizeParam'            => 'page_size_param',
        'entityClass'              => 'entity_class',
        'collectionClass'          => 'collection_class',
    );

    /**
     * Allowed REST update options that are arrays
     *
     * @var array
     */
    protected $restArrayUpdateOptions = array(
        'collectionHttpMethods'    => 'collection_http_methods',
        'collectionQueryWhitelist' => 'collection_query_whitelist',
        'entityHttpMethods'      => 'entity_http_methods',
    );
    
    protected $doctrineHydratorOptions = array(
    	'entityClass'              => 'entity_class',
    	'objectManager'            => 'object_manager',
    	'byValue'                  => 'by_value',
    	'useGeneratedHydrator'     => 'use_generated_hydrator',
    	'hydratorStrategies'       => 'hydrator_strategies',
    );
    
    /**
     * @var FilterChain
     */
    protected $routeNameFilter;

    /**
     * @param ModuleEntity   $moduleEntity
     * @param ModuleUtils    $modules
     * @param ConfigResource $config
     */
    public function __construct(ModuleEntity $moduleEntity, ModuleUtils $modules, ConfigResource $config)
    {
        $this->module         = $moduleEntity->getName();
        $this->moduleEntity   = $moduleEntity;
        $this->modules        = $modules;
        $this->configResource = $config;
        $this->modulePath     = $modules->getModulePath($this->module);
    }

    /**
     * Determine if the given entity is doctrine-connected, and, if so, recast to a DoctrineRestServiceEntity
     *
     * @param  \Zend\EventManager\Event       $e
     * @return null|DoctrineRestServiceEntity
     */
    // @codeCoverageIgnoreStart

    public static function onFetch($e)
    {
        $entity = $e->getParam('entity', false);
        if (!$entity) {
            // No entity; nothing to do
            return;
        }

        $config = $e->getParam('config', array());
        if (!isset($config['zf-apigility'])
            || !isset($config['zf-apigility']['doctrine-connected'])
            || !isset($config['zf-apigility']['doctrine-connected'][$entity->resourceClass])
        ) {
            // No DB-connected configuration for this service; nothing to do
            return;
        }
        
        //TODO : Move hydrators handling into separate model ?
        $configResource = $config['zf-apigility']['doctrine-connected'][$entity->resourceClass];
        
        if (isset($config['doctrine-hydrator']) && isset($config['doctrine-hydrator'][$configResource['hydrator']])) {
        	$configHydrator = $config['doctrine-hydrator'][$configResource['hydrator']];
	        $config = array_merge($configResource,$configHydrator);
        } else {
        	$config = $configResource;
        }

        $doctrineEntity = new DoctrineRestServiceEntity();
        $doctrineEntity->exchangeArray(array_merge($entity->getArrayCopy(), $config));

        return $doctrineEntity;
    }

    /**
     * Allow read-only access to properties
     *
     * @param  string               $name
     * @return mixed
     * @throws \OutOfRangeException
     */
    public function __get($name)
    {
        if (!isset($this->{$name})) {
            throw new \OutOfRangeException(sprintf(
                'Cannot locate property by name of "%s"',
                $name
            ));
        }

        return $this->{$name};
    }

    // @codeCoverageIgnoreEnd

    protected $serviceManager;

    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;

        return $this;
    }

    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set the EventManager instance
     *
     * @param  EventManagerInterface $events
     * @return self
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $events->setIdentifiers(array(
            __CLASS__,
            get_class($this),
        ));
        $this->events = $events;

        return $this;
    }

    /**
     * Retrieve the EventManager instance
     *
     * Lazy instantiates one if none currently registered
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!$this->events) {
            $this->setEventManager(new EventManager());
        }

        return $this->events;
    }

    /**
     * @param  string                  $controllerService
     * @return RestServiceEntity|false
     */
    public function fetch($controllerService)
    {
        $config = $this->configResource->fetch(true);

        if (!isset($config['zf-rest'])
            || !isset($config['zf-rest'][$controllerService])
        ) {
            // @codeCoverageIgnoreStart
            throw new Exception\RuntimeException(sprintf(
                'Could not find REST resource by name of %s',
                $controllerService
            ), 404);
            // @codeCoverageIgnoreEnd
        }

        $restConfig = $config['zf-rest'][$controllerService];

        $restConfig['controllerServiceName'] = $controllerService;
        $restConfig['module']                = $this->module;
        $restConfig['resource_class']        = $restConfig['listener'];
        unset($restConfig['listener']);
        $entity = new DoctrineRestServiceEntity();
        $entity->exchangeArray($restConfig);

        $this->getRouteInfo($entity, $config);
        $this->mergeContentNegotiationConfig($controllerService, $entity, $config);
        $this->mergeHalConfig($controllerService, $entity, $config);

        // Trigger an event, allowing a listener to alter the entity and/or
        // curry a new one.
        // @codeCoverageIgnoreStart
        $eventResults = $this->getEventManager()->trigger(__FUNCTION__, $this, array(
            'entity' => $entity,
            'config' => $config,
        ), function ($r) {
            return ($r instanceof DoctrineRestServiceEntity);
        });
        if ($eventResults->stopped()) {
            return $eventResults->last();
        }

        // @codeCoverageIgnoreEnd
        return $entity;
    }

    /**
     * Fetch all services
     *
     * @return RestServiceEntity[]
     */
    public function fetchAll($version = null)
    {
        $config = $this->configResource->fetch(true);
        if (!isset($config['zf-rest'])) {
            // @codeCoverageIgnoreStart
            return array();
            // @codeCoverageIgnoreEnd
        }
<commit_msg>Generates service name on REST fetch if not found<commit_after><?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2013 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\Apigility\Doctrine\Admin\Model;

use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\Filter\FilterChain;
use Zend\View\Model\ViewModel;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use ZF\Apigility\Admin\Exception;
use ZF\Configuration\ConfigResource;
use ZF\Configuration\ModuleUtils;
use ZF\Rest\Exception\CreationException;
use Zf\Apigility\Admin\Model\ModuleEntity;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use ZF\ApiProblem\ApiProblem;

class DoctrineRestServiceModel implements EventManagerAwareInterface, ServiceManagerAwareInterface
{
    /**
     * @var ConfigResource
     */
    protected $configResource;

    /**
     * @var EventManagerInterface
     */
    protected $events;

    /**
     * @var string
     */
    protected $module;

    /**
     * @var ModuleEntity
     */
    protected $moduleEntity;

    /**
     * @var string
     */
    protected $modulePath;

    /**
     * @var ModuleUtils
     */
    protected $modules;

    /**
     * @var PhpRenderer
     */
    protected $renderer;

    /**
     * Allowed REST update options that are scalars
     *
     * @var array
     */
    protected $restScalarUpdateOptions = array(
        'pageSize'                 => 'page_size',
        'pageSizeParam'            => 'page_size_param',
        'entityClass'              => 'entity_class',
        'collectionClass'          => 'collection_class',
    );

    /**
     * Allowed REST update options that are arrays
     *
     * @var array
     */
    protected $restArrayUpdateOptions = array(
        'collectionHttpMethods'    => 'collection_http_methods',
        'collectionQueryWhitelist' => 'collection_query_whitelist',
        'entityHttpMethods'      => 'entity_http_methods',
    );
    
    protected $doctrineHydratorOptions = array(
    	'entityClass'              => 'entity_class',
    	'objectManager'            => 'object_manager',
    	'byValue'                  => 'by_value',
    	'useGeneratedHydrator'     => 'use_generated_hydrator',
    	'hydratorStrategies'       => 'hydrator_strategies',
    );
    
    /**
     * @var FilterChain
     */
    protected $routeNameFilter;

    /**
     * @param ModuleEntity   $moduleEntity
     * @param ModuleUtils    $modules
     * @param ConfigResource $config
     */
    public function __construct(ModuleEntity $moduleEntity, ModuleUtils $modules, ConfigResource $config)
    {
        $this->module         = $moduleEntity->getName();
        $this->moduleEntity   = $moduleEntity;
        $this->modules        = $modules;
        $this->configResource = $config;
        $this->modulePath     = $modules->getModulePath($this->module);
    }

    /**
     * Determine if the given entity is doctrine-connected, and, if so, recast to a DoctrineRestServiceEntity
     *
     * @param  \Zend\EventManager\Event       $e
     * @return null|DoctrineRestServiceEntity
     */
    // @codeCoverageIgnoreStart

    public static function onFetch($e)
    {
        $entity = $e->getParam('entity', false);
        if (!$entity) {
            // No entity; nothing to do
            return;
        }

        $config = $e->getParam('config', array());
        if (!isset($config['zf-apigility'])
            || !isset($config['zf-apigility']['doctrine-connected'])
            || !isset($config['zf-apigility']['doctrine-connected'][$entity->resourceClass])
        ) {
            // No DB-connected configuration for this service; nothing to do
            return;
        }
        
        //TODO : Move hydrators handling into separate model ?
        $configResource = $config['zf-apigility']['doctrine-connected'][$entity->resourceClass];
        
        if (isset($config['doctrine-hydrator']) && isset($config['doctrine-hydrator'][$configResource['hydrator']])) {
        	$configHydrator = $config['doctrine-hydrator'][$configResource['hydrator']];
	        $config = array_merge($configResource,$configHydrator);
        } else {
        	$config = $configResource;
        }

        $doctrineEntity = new DoctrineRestServiceEntity();
        $doctrineEntity->exchangeArray(array_merge($entity->getArrayCopy(), $config));

        return $doctrineEntity;
    }

    /**
     * Allow read-only access to properties
     *
     * @param  string               $name
     * @return mixed
     * @throws \OutOfRangeException
     */
    public function __get($name)
    {
        if (!isset($this->{$name})) {
            throw new \OutOfRangeException(sprintf(
                'Cannot locate property by name of "%s"',
                $name
            ));
        }

        return $this->{$name};
    }

    // @codeCoverageIgnoreEnd

    protected $serviceManager;

    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;

        return $this;
    }

    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set the EventManager instance
     *
     * @param  EventManagerInterface $events
     * @return self
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $events->setIdentifiers(array(
            __CLASS__,
            get_class($this),
        ));
        $this->events = $events;

        return $this;
    }

    /**
     * Retrieve the EventManager instance
     *
     * Lazy instantiates one if none currently registered
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!$this->events) {
            $this->setEventManager(new EventManager());
        }

        return $this->events;
    }

    /**
     * @param  string                  $controllerService
     * @return RestServiceEntity|false
     */
    public function fetch($controllerService)
    {
        $config = $this->configResource->fetch(true);

        if (!isset($config['zf-rest'])
            || !isset($config['zf-rest'][$controllerService])
        ) {
            // @codeCoverageIgnoreStart
            throw new Exception\RuntimeException(sprintf(
                'Could not find REST resource by name of %s',
                $controllerService
            ), 404);
            // @codeCoverageIgnoreEnd
        }

        $restConfig = $config['zf-rest'][$controllerService];

        $restConfig['controllerServiceName'] = $controllerService;
        $restConfig['module']                = $this->module;
        $restConfig['resource_class']        = $restConfig['listener'];
        unset($restConfig['listener']);
        $entity = new DoctrineRestServiceEntity();
        $entity->exchangeArray($restConfig);

        $this->getRouteInfo($entity, $config);
        $this->mergeContentNegotiationConfig($controllerService, $entity, $config);
        $this->mergeHalConfig($controllerService, $entity, $config);

        // Trigger an event, allowing a listener to alter the entity and/or
        // curry a new one.
        // @codeCoverageIgnoreStart
        $eventResults = $this->getEventManager()->trigger(__FUNCTION__, $this, array(
            'entity' => $entity,
            'config' => $config,
        ), function ($r) {
            return ($r instanceof DoctrineRestServiceEntity);
        });
        if ($eventResults->stopped()) {
            return $eventResults->last();
        }
        
        if (!isset($entity->serviceName)
        		|| empty($entity->serviceName)
        ) {
        	$serviceName = $controllerService;
        	$q = preg_quote('\\');
        	if (preg_match('#' . $q . 'V[^' . $q . ']+' . $q . 'Rest' . $q . '(?<service>[^' . $q . ']+)' . $q . 'Controller#', $controllerService, $matches)) {
        		$serviceName = $matches['service'];
        	}
        	$entity->exchangeArray(array(
        		'service_name' => $serviceName,
        	));
        }

        // @codeCoverageIgnoreEnd
        return $entity;
    }

    /**
     * Fetch all services
     *
     * @return RestServiceEntity[]
     */
    public function fetchAll($version = null)
    {
        $config = $this->configResource->fetch(true);
        if (!isset($config['zf-rest'])) {
            // @codeCoverageIgnoreStart
            return array();
            // @codeCoverageIgnoreEnd
        }

{'fraction_non_alphanumeric': 0.1261816441306689, 'fraction_numerical': 0.001076941486179251, 'mean_word_length': 2.2070222563315425, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 108, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4929612', 'n_tokens_mistral': 4701, 'n_tokens_neox': 4538, 'n_words': 896}