/** * @return FilterChain */ protected function getCamelCaseToUnderscoreFilter() { if (static::$camelCaseToUnderscoreFilter instanceof FilterChain) { return static::$camelCaseToUnderscoreFilter; } $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore'); $filter->attachByName('StringToLower'); return static::$camelCaseToUnderscoreFilter = $filter; }
public function testDoctrineService() { $serviceManager = $this->getApplication()->getServiceManager(); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $tool = new SchemaTool($em); $res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata()); // Create DB $resourceDefinition = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "Artist", "entityClass" => "Db\\Entity\\Artist", "routeIdentifierName" => "artist_id", "entityIdentifierName" => "id", "routeMatch" => "/db-test/artist"); $this->resource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceResource'); $this->resource->setModuleName('DbApi'); $entity = $this->resource->create($resourceDefinition); $this->assertInstanceOf('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceEntity', $entity); $controllerServiceName = $entity->controllerServiceName; $this->assertNotEmpty($controllerServiceName); $this->assertContains('DbApi\\V1\\Rest\\Artist\\Controller', $controllerServiceName); $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower'); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $metadataFactory = $em->getMetadataFactory(); $entityMetadata = $metadataFactory->getMetadataFor("Db\\Entity\\Artist"); foreach ($entityMetadata->associationMappings as $mapping) { switch ($mapping['type']) { case 4: $rpcServiceResource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRpcServiceResource'); $rpcServiceResource->setModuleName('DbApi'); $rpcServiceResource->create(array('service_name' => 'Artist' . $mapping['fieldName'], 'route' => '/db-test/artist[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]', 'http_methods' => array('GET', 'PUT', 'POST'), 'options' => array('target_entity' => $mapping['targetEntity'], 'source_entity' => $mapping['sourceEntity'], 'field_name' => $mapping['fieldName']), 'selector' => 'custom selector')); break; default: break; } } }
public function testAllowsConnectingViaClassShortName() { $chain = new FilterChain(); $chain->attachByName('string_trim', array('encoding' => 'utf-8'), 100)->attachByName('strip_tags')->attachByName('string_to_lower', array('encoding' => 'utf-8'), 900); $value = '<a name="foo"> ABC </a>'; $valueExpected = 'abc'; $this->assertEquals($valueExpected, $chain->filter($value)); }
/** * Retrieve and/or initialize the normalization filter chain * * @return FilterChain */ protected function getNormalizationFilter() { if ($this->filter instanceof FilterChain) { return $this->filter; } $this->filter = new FilterChain(); $this->filter->attachByName('WordCamelCaseToDash')->attachByName('StringToLower'); return $this->filter; }
/** * @return FilterChain */ private function filterNamespaceToDirectory() { if (null === $this->filterNamespaceToDirectory) { $this->filterNamespaceToDirectory = new FilterChain(); $this->filterNamespaceToDirectory->attachByName('wordseparatortocamelcase', ['separator' => '\\']); $this->filterNamespaceToDirectory->attachByName('wordcamelcasetoseparator', ['separator' => '/']); } return $this->filterNamespaceToDirectory; }
/** * Retrieve the filter chain for generating the route name * * @return FilterChain */ protected function getRouteNameFilter() { if ($this->routeNameFilter instanceof FilterChain) { return $this->routeNameFilter; } $this->routeNameFilter = new FilterChain(); $this->routeNameFilter->attachByName('Word\\CamelCaseToDash')->attachByName('StringToLower'); return $this->routeNameFilter; }
/** * @return FilterChain */ private function filterNamespaceToDirectory() { if (null === $this->filterNamespaceToDirectory) { $this->filterNamespaceToDirectory = new FilterChain(); $this->filterNamespaceToDirectory->attachByName('wordseparatortoseparator', ['search_separator' => '\\', 'replacement_separator' => '|']); $this->filterNamespaceToDirectory->attachByName('wordseparatortoseparator', ['search_separator' => '|', 'replacement_separator' => DIRECTORY_SEPARATOR]); } return $this->filterNamespaceToDirectory; }
/** * Retrieve the filter chain for generating the route name * * @return FilterChain */ protected function getRouteNameFilter() { if ($this->routeNameFilter instanceof FilterChain) { return $this->routeNameFilter; } $this->routeNameFilter = new FilterChain(); $this->routeNameFilter->attachByName(CamelCaseToDash::class)->attachByName(StringToLower::class); return $this->routeNameFilter; }
public function testAllowsConnectingViaClassShortName() { if (!function_exists('mb_strtolower')) { $this->markTestSkipped('mbstring required'); } $chain = new FilterChain(); $chain->attachByName('string_trim', null, 100)->attachByName('strip_tags')->attachByName('string_to_lower', array('encoding' => 'utf-8'), 900); $value = '<a name="foo"> ABC </a>'; $valueExpected = 'abc'; $this->assertEquals($valueExpected, $chain->filter($value)); }
public function extract($value) { if (!method_exists($value, 'getTypeClass')) { return; } $config = $this->getMetadataMap()[$value->getTypeClass()->name]; $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower'); // Better way to create mapping name? // FIXME: use zf-hal collection_name $link = new Link('self'); $link->setRoute($config['route_name']); $link->setRouteParams(array('id' => null)); $filterValue = array('field' => $value->getMapping()['mappedBy'] ?: $value->getMapping()['inversedBy'], 'type' => isset($value->getMapping()['joinTable']) ? 'ismemberof' : 'eq', 'value' => $value->getOwner()->getId()); $link->setRouteOptions(array('query' => array($this->getFilterKey() => array($filterValue)))); $linkCollection = new LinkCollection(); $linkCollection->add($link); $halEntity = new HalEntity(new stdClass()); $halEntity->setLinks($linkCollection); return $halEntity; }
public function extract($value) { $config = $this->getServiceManager()->get('Config'); if (!method_exists($value, 'getTypeClass') || !isset($config['zf-hal']['metadata_map'][$value->getTypeClass()->name])) { return; } $config = $config['zf-hal']['metadata_map'][$value->getTypeClass()->name]; $mapping = $value->getMapping(); $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower'); $link = new Link($filter($mapping['fieldName'])); $link->setRoute($config['route_name']); $link->setRouteParams(array('id' => null)); if (isset($config['zf-doctrine-querybuilder-options']['filter_key'])) { $filterKey = $config['zf-doctrine-querybuilder-options']['filter_key']; } else { $filterKey = 'filter'; } $link->setRouteOptions(array('query' => array($filterKey => array(array('field' => $mapping['mappedBy'], 'type' => 'eq', 'value' => $value->getOwner()->getId()))))); return $link; }
public function testBuildOrmApi() { $serviceManager = $this->getApplication()->getServiceManager(); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $tool = new SchemaTool($em); $res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata()); // Create DB $resource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceResource'); $artistResourceDefinition = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "Artist", "entityClass" => "ZFTestApigilityDb\\Entity\\Artist", "routeIdentifierName" => "artist_id", "entityIdentifierName" => "id", "routeMatch" => "/test/rest/artist", "collectionHttpMethods" => array(0 => 'GET', 1 => 'POST', 2 => 'PATCH', 3 => 'DELETE')); $artistResourceDefinitionWithNonKeyIdentifer = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "ArtistByName", "entityClass" => "ZFTestApigilityDb\\Entity\\Artist", "routeIdentifierName" => "artist_name", "entityIdentifierName" => "name", "routeMatch" => "/test/rest/artist-by-name", "collectionHttpMethods" => array(0 => 'GET')); // This route is what should be an rpc service, but an user could do $albumResourceDefinition = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "Album", "entityClass" => "ZFTestApigilityDb\\Entity\\Album", "routeIdentifierName" => "album_id", "entityIdentifierName" => "id", "routeMatch" => "/test/rest[/artist/:artist_id]/album[/:album_id]", "collectionHttpMethods" => array(0 => 'GET', 1 => 'POST', 2 => 'PATCH', 3 => 'DELETE')); $resource->setModuleName('ZFTestApigilityDbApi'); $artistEntity = $resource->create($artistResourceDefinition); $artistEntity = $resource->create($artistResourceDefinitionWithNonKeyIdentifer); $albumEntity = $resource->create($albumResourceDefinition); $this->assertInstanceOf('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceEntity', $artistEntity); $this->assertInstanceOf('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceEntity', $albumEntity); // Build relation $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower'); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $metadataFactory = $em->getMetadataFactory(); $entityMetadata = $metadataFactory->getMetadataFor("ZFTestApigilityDb\\Entity\\Artist"); $rpcServiceResource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRpcServiceResource'); $rpcServiceResource->setModuleName('ZFTestApigilityDbApi'); foreach ($entityMetadata->associationMappings as $mapping) { switch ($mapping['type']) { case 4: $rpcServiceResource->create(array('service_name' => 'Artist' . $mapping['fieldName'], 'route' => '/test/artist[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]', 'http_methods' => array('GET', 'PUT', 'POST'), 'options' => array('target_entity' => $mapping['targetEntity'], 'source_entity' => $mapping['sourceEntity'], 'field_name' => $mapping['fieldName']), 'selector' => 'custom selector')); break; default: break; } } }
public function testClone() { $chain = new FilterChain(); $clone = clone $chain; $chain->attachByName('strip_tags'); $this->assertCount(0, $clone); }
public function index18Action() { echo "<h3 style='color:red;font-weight:bold'>" . __METHOD__ . "</h3>"; $input = " Trongle123123-Handsome-Talent "; $filterChain = new ZFilter\FilterChain(); $filterChain->attachByName("StringTrim"); $filterChain->attachByName("PregReplace", array("pattern" => "#[0-9]#", "replacement" => "!")); $filterChain->attachByName("Word\\DashToUnderscore"); $output = $filterChain->filter($input); echo "<h2>Input: {$input}</h2><br>"; echo "<h2>Output : {$output}</h2>"; return false; }
/** * @param FilterChain $chain * @param array|Traversable $filters * @throws Exception\RuntimeException * @return void */ protected function populateFilters(FilterChain $chain, $filters) { foreach ($filters as $filter) { if (is_object($filter) || is_callable($filter)) { $chain->attach($filter); continue; } if (is_array($filter)) { if (!isset($filter['name'])) { throw new Exception\RuntimeException('Invalid filter specification provided; does not include "name" key'); } $name = $filter['name']; $priority = isset($filter['priority']) ? $filter['priority'] : FilterChain::DEFAULT_PRIORITY; $options = []; if (isset($filter['options'])) { $options = $filter['options']; } $chain->attachByName($name, $options, $priority); continue; } throw new Exception\RuntimeException('Invalid filter specification provided; was neither a filter instance nor an array specification'); } }
/** * Sanitizes action name to use in route. * * @param string $name * @return string */ protected function filterActionMethodName($name) { $filter = new FilterChain(); $filter->attachByName('Zend\\Filter\\Word\\CamelCaseToDash'); $filter->attachByName('StringToLower'); return rtrim(preg_replace('/action$/', '', $filter->filter($name)), '-'); }
/** * Constructor * * Sets the class, and passes any options provided to the appropriate * setter methods, after first converting them to lowercase and stripping * underscores. * * If the class does not exist, raises an exception. * * @param string $class * @param array $options * @param HydratorPluginManager $hydrators * @throws Exception\InvalidArgumentException */ public function __construct($class, array $options = [], HydratorPluginManager $hydrators = null) { $filter = new FilterChain(); $filter->attachByName('WordUnderscoreToCamelCase')->attachByName('StringToLower'); if (!class_exists($class)) { throw new Exception\InvalidArgumentException(sprintf('Class provided to %s must exist; received "%s"', __CLASS__, $class)); } $this->class = $class; if (null !== $hydrators) { $this->hydrators = $hydrators; } $legacyIdentifierName = false; foreach ($options as $key => $value) { $filteredKey = $filter($key); if ($filteredKey === 'class') { continue; } // Strip "name" from route_name key // Rename "resourceroutename" and "resourceroute" to "entityroute". // Don't generically strip all 'name's if ($filteredKey === 'routename') { $filteredKey = 'route'; } if ($filteredKey === 'resourceroutename' || $filteredKey === 'resourceroute') { $filteredKey = 'entityroute'; } if ($filteredKey === 'entityroutename') { $filteredKey = 'entityroute'; } // Fix BC issue: s/identifier_name/route_identifier_name/ if ($filteredKey === 'identifiername') { $legacyIdentifierName = $value; continue; } $method = 'set' . $filteredKey; if (method_exists($this, $method)) { $this->{$method}($value); } else { throw new Exception\InvalidArgumentException(sprintf('Unhandled option passed to Metadata constructor: %s %s', $method, $key)); } } if ($legacyIdentifierName && !$this->routeIdentifierName) { $this->setRouteIdentifierName($legacyIdentifierName); } if ($legacyIdentifierName && !$this->entityIdentifierName) { $this->setEntityIdentifierName($legacyIdentifierName); } }
/** * Retrieve and/or initialize the normalization filter chain * * @return FilterChain */ protected function getRouteNormalizationFilter() { if (isset($this->filters['route']) && $this->filters['route'] instanceof FilterChain) { return $this->filters['route']; } $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToDash')->attachByName('StringToLower'); $this->filters['route'] = $filter; return $filter; }
public function apiAction() { $moduleName = 'DbApi'; $objectManagerAlias = 'doctrine.entitymanager.orm_default'; $routePrefix = 'api'; $useEntityNamespacesForRoute = false; if (!$this->getServiceLocator()->get('Zend\\ModuleManager\\ModuleManager')->getModule($moduleName)) { $this->getConsole()->writeLine(sprintf('Module %s is not loaded. Did you forget to run "./app build api module" ?', $moduleName), ColorInterface::YELLOW); return; } // Build resources $objectManager = $this->getServiceLocator()->get($objectManagerAlias); $metadataFactory = $objectManager->getMetadataFactory(); foreach ($metadataFactory->getAllMetadata() as $metadata) { if (substr($metadata->getName(), strlen($metadata->namespace) + 1, 8) == 'Abstract') { continue; } $entityClassNames[] = $metadata->getName(); } // Get the route prefix and remove any / from ends of string if (!$routePrefix) { $routePrefix = ''; } else { while (substr($routePrefix, 0, 1) == '/') { $routePrefix = substr($routePrefix, 1); } while (substr($routePrefix, strlen($routePrefix) - 1) == '/') { $routePrefix = substr($routePrefix, 0, strlen($routePrefix) - 1); } } $objectManager = $this->getServiceLocator()->get($objectManagerAlias); $metadataFactory = $objectManager->getMetadataFactory(); $serviceResource = $this->getServiceLocator()->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceResource'); // Generate a session id for results on next page $results = []; foreach ($metadataFactory->getAllMetadata() as $entityMetadata) { if (!in_array($entityMetadata->name, $entityClassNames)) { continue; } $resourceName = substr($entityMetadata->name, strlen($entityMetadata->namespace) + 1); if (sizeof($entityMetadata->identifier) !== 1) { throw new \Exception($entityMetadata->name . " does not have exactly one identifier and cannot be generated"); } $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower'); if ($useEntityNamespacesForRoute) { $route = '/' . $routePrefix . '/' . $filter(str_replace('\\', '/', $entityMetadata->name)); } else { $route = '/' . $routePrefix . '/' . $filter($resourceName); } $serviceResource->setModuleName($moduleName); $serviceResource->create(array('objectManager' => $objectManagerAlias, 'serviceName' => $resourceName, 'entityClass' => $entityMetadata->name, 'pageSizeParam' => 'limit', 'routeIidentifierName' => $filter($resourceName) . '_id', 'entityIdentifierName' => array_pop($entityMetadata->identifier), 'routeMatch' => $route)); foreach ($entityMetadata->associationMappings as $mapping) { switch ($mapping['type']) { case 4: $rpcServiceResource = $this->getServiceLocator()->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRpcServiceResource'); $rpcServiceResource->setModuleName($moduleName); $rpcServiceResource->create(array('service_name' => $resourceName . '' . $mapping['fieldName'], 'route' => $mappingRoute = $route . '[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]', 'http_methods' => array('GET'), 'options' => array('target_entity' => $mapping['targetEntity'], 'source_entity' => $mapping['sourceEntity'], 'field_name' => $mapping['fieldName']))); $results[$entityMetadata->name . $mapping['fieldName']] = $mappingRoute; break; default: break; } } $results[$entityMetadata->name] = $route; } return print_r($results, true) . "\nResources have been created.\n"; }
/** * @group ZF-412 */ public function testCanAttachMultipleFiltersOfTheSameTypeAsDiscreteInstances() { $chain = new FilterChain(); $chain->attachByName('PregReplace', array('pattern' => '/Foo/', 'replacement' => 'Bar')); $chain->attachByName('PregReplace', array('pattern' => '/Bar/', 'replacement' => 'PARTY')); $this->assertEquals(2, count($chain)); $filters = $chain->getFilters(); $compare = null; foreach ($filters as $filter) { $this->assertNotSame($compare, $filter); $compare = $filter; } $this->assertEquals('Tu et PARTY', $chain->filter('Tu et Foo')); }