/** * Inject Table defined by type to PizzaService when triggered * * @param EventInterface */ public function onTableSet(EventInterface $e) { $type = $e->getParam('type', 'rentals'); $tableName = StaticFilter::execute($type, 'wordunderscoretocamelcase'); $service = $this->serviceLocator->get('Rentals\\Service\\Rentals'); $form = $this->serviceLocator->get('Rentals\\Table\\' . $tableName); $service->setTable($form, $type); }
public function cityAction() { $id = StaticFilter::execute($this->params()->fromRoute('id'), ToInt::class); $city = $this->worldService->getCityById($id); if (!$city) { throw new \Exception('No City found with ID ' . $id); } $country = $this->worldService->getCountryByCode($city->getCountryCode()); return new ViewModel(['city' => $city, 'country' => $country]); }
/** * Manage database schema */ public function schemaManagerAction() { $request = $this->getRequest(); // Set up logger. Log level is already validated by route. $priority = \Zend\Filter\StaticFilter::execute($request->getParam('loglevel', 'info'), 'Library\\LogLevel'); $writer = new \Zend\Log\Writer\Stream('php://stderr'); $writer->addFilter('priority', array('priority' => $priority)); $writer->setFormatter('simple', array('format' => '%priorityName%: %message%')); $this->_logger->addWriter($writer); $this->_schemaManager->updateAll($request->getParam('prune')); }
/** * Test filter() method */ public function testFilter() { // 2 common example characters $enDashBad = ""; $enDashGood = "–"; $tmBad = ""; $tmGood = "™"; // Test 1 character twice to check repeated replacements $input = $enDashBad . $tmBad . $enDashBad; $expected = $enDashGood . $tmGood . $enDashGood; $this->assertEquals($expected, \Zend\Filter\StaticFilter::execute($input, 'Library\\FixEncodingErrors')); }
public function exchangeArray(array $array) { foreach ($array as $key => $value) { if (empty($value)) { continue; } $method = 'set' . StaticFilter::execute($key, 'wordunderscoretocamelcase'); if (!method_exists($this, $method)) { continue; } $this->{$method}($value); } }
/** * Generate an array copy from property values */ public function getArrayCopy() { $data = []; foreach (get_object_vars($this) as $key => $value) { $getMethod = 'get' . ucfirst($key); $arrayKey = StaticFilter::execute($key, 'WordCamelCaseToUnderscore'); $arrayKey = StaticFilter::execute($arrayKey, 'StringToLower'); if (method_exists($this, $getMethod)) { $data[$arrayKey] = $this->{$getMethod}(); } } return $data; }
/** * Create a new DB-Connected REST service * * @param DbConnectedRestServiceEntity $entity * @return DbConnectedRestServiceEntity */ public function createService(DbConnectedRestServiceEntity $entity) { $restModel = $this->restModel; $resourceName = StaticFilter::execute($entity->tableName, 'WordUnderscoreToCamelCase'); $resourceClass = sprintf( '%s\\V%s\\Rest\\%s\\%sResource', $this->restModel->module, $this->restModel->moduleEntity->getLatestVersion(), $resourceName, $resourceName ); $controllerService = $restModel->createControllerServiceName($resourceName); $entityClass = $restModel->createEntityClass($resourceName, 'entity-db-connected'); $collectionClass = $restModel->createCollectionClass($resourceName); $routeName = $restModel->createRoute( $resourceName, $entity->routeMatch, $entity->routeIdentifierName, $controllerService ); $mediaType = $restModel->createMediaType(); $entity->exchangeArray(array( 'collection_class' => $collectionClass, 'controller_service_name' => $controllerService, 'entity_class' => $entityClass, 'module' => $restModel->module, 'resource_class' => $resourceClass, 'route_name' => $routeName, 'accept_whitelist' => array( $mediaType, 'application/hal+json', 'application/json', ), 'content_type_whitelist' => array( $mediaType, 'application/json', ), )); $restModel->createRestConfig($entity, $controllerService, $resourceClass, $routeName); $restModel->createContentNegotiationConfig($entity, $controllerService); $restModel->createHalConfig($entity, $entityClass, $collectionClass, $routeName); $this->createDbConnectedConfig($entity); return $entity; }
public function filter($value) { /** cach 01 */ // $filterChain = new \Zend\Filter\FilterChain(); // $filterChain // ->attach(new \Zend\I18n\Filter\Alnum(true)) // ->attach(new \Zend\Filter\StringTrim()) // ->attach(new \Zend\Filter\PregReplace(array( // 'pattern' => '#\s+#', // 'replacement' => ' ' // ))) // ->attach(new \ZendVN\Filter\RemoveCircumflex()) // ->attach(new \Zend\Filter\StringToLower()) // ->attach(new \Zend\Filter\Word\SeparatorToDash()) // ; // return $filterChain->filter($value); $output = \Zend\Filter\StaticFilter::execute($value, 'alnum'); return $output; }
public function index23Action() { echo "<h3 style='color:red;font-weight:bold'>" . __METHOD__ . "</h3>"; $input = "www.zend.vn/ Khóa học lập trình Zend Framework \$#%#\$%@ cung CẤP kiến thức căn bản và chuyên sâu về Zend Framework"; $arr = explode(".vn/", $input); $output = $arr[0] . ".vn/" . StaticFilter::execute($arr[1], "CreateLinkFriendly") . ".html"; echo "<h2>Input: {$input}</h2><br>"; echo "<h2>Output :{$output}</h2>"; return false; }
public function index34Action() { $input = 'http://www.zend.vn/Khóa học lập trình Zend Framework !@#$%^&*()_+ cung cấp những kiển thức căn bản và chuyên sâu về Zend Framework'; // http://www.zend.vn/khoa-hoc-lap-trinh-zend-framework-cng-cap-nhung-kien-thuc-can-ban-va-chuyen-sau-ve-zend-framework.html $newArr = explode('.vn/', $input); $output = \Zend\Filter\StaticFilter::execute($newArr[1], 'CreateURL'); echo "<h3>" . $input . "</h3>"; echo "<h3>" . $newArr[0] . 'vn/' . $output . "</h3>"; return false; }
/** * Ensures that if we specify a validator class basename that doesn't * exist in the namespace, get() throws an exception. * * Refactored to conform with ZF-2724. * * @group ZF-2724 */ public function testStaticFactoryClassNotFound() { $this->setExpectedException('\\Zend\\Filter\\Exception', 'not found'); StaticFilter::execute('1234', 'UnknownFilter'); }
/** * Validator callback for subkeys input * * @internal * @param string $value * @param array $context * @return bool TRUE if 'name' is empty or 'name' and 'subkeys' are not empty */ public function validateEmptySubkeys($value, $context) { $name = \Zend\Filter\StaticFilter::execute($context['name'], 'StringTrim'); if ($name != '' and $value == '') { return false; } else { return true; } }
}; } } } else { $headers[$column] = $allHeaders[$column]; } } $filter = $this->filter; $count = count($this->clients); if ($filter) { $search = $this->search; if ($this->isCustomSearch) { // Display the number of results and links to edit the filter or add it // to a group. if ($search instanceof \DateTime) { $search = $search->format('Y-m-d'); } $params = array('filter' => $filter, 'search' => $search, 'operator' => $this->operator, 'invert' => $this->invert); $header = sprintf($this->translate('%d matches'), $count) . "<br>\n" . $this->htmlTag('a', $this->translate('Edit filter'), array('href' => $this->consoleUrl('client', 'search', $params)), true) . "\n \n" . $this->htmlTag('a', $this->translate('Save to group'), array('href' => $this->consoleUrl('group', 'add', $params)), true); } else { // For fixed filters, print a nicer description. if ($filter == 'Software') { $search = \Zend\Filter\StaticFilter::execute($search, 'Library\\FixEncodingErrors'); } $header = $this->filterDescription($filter, $search, $count); } } else { $header = sprintf($this->translate('Number of clients: %d'), $count); } print $this->htmlTag('p', $header, array('class' => 'textcenter')); print $this->table($this->clients, $headers, array('order' => $this->order, 'direction' => $this->direction), $renderCallbacks, $columnClasses);
/** * Filter underscore to camel case * * @param string $text * * @return string */ public function filterUnderscoreToCamelCase($text) { $text = StaticFilter::execute($text, 'Word\\UnderscoreToCamelCase'); return $text; }
/** * Filter camel case to underscore * * @param string $text * * @return string */ protected function filterCamelCaseToUnderscore($text) { $text = StaticFilter::execute($text, 'Word\\CamelCaseToUnderscore'); $text = StaticFilter::execute($text, 'StringToLower'); return $text; }
/** * @param $module * @param $version * @param $tableName * @return bool */ protected function moduleHasService($module, $version, $tableName) { $resourceName = StaticFilter::execute($tableName, 'WordUnderscoreToCamelCase'); $resourceClass = sprintf('%s\\V%s\\Rest\\%s\\%sResource', $module, $version, $resourceName, $resourceName); return $this->getServiceLocator()->has($resourceClass); }
/** * @requires PHP 7.0 */ public function testFilterInvalidInput() { $this->setExpectedException('InvalidArgumentException', 'Input does not appear to be a zlib stream'); \Zend\Filter\StaticFilter::execute('not a zlib stream', 'Protocol\\InventoryDecode'); }
/** * Add indexAction() method for DeleteController * * @param $repositoryClass * @param $formClass */ protected function addDeleteControllerAction($repositoryClass, $formClass) { // prepare some params $formParam = lcfirst($formClass); $underscoredParam = strtolower(StaticFilter::execute(str_replace('Entity', '', $this->entityClass), 'WordCamelCaseToUnderscore')); $dashedParam = strtolower(StaticFilter::execute($this->paramModule, 'WordCamelCaseToDash')); $dashedModule = strtolower(StaticFilter::execute($this->paramModule, 'WordCamelCaseToUnderscore')); $noFoundMessage = $dashedModule . '_message_' . $underscoredParam . '_not_found'; $deleteMessage = $dashedModule . '_message_' . $underscoredParam . '_deleting_possible'; $successMessage = $dashedModule . '_message_' . $underscoredParam . '_deleting_success'; $failedMessage = $dashedModule . '_message_' . $underscoredParam . '_deleting_failed'; // prepare entity params $entityParam = lcfirst($this->entityClass); $body = ['$id = $this->params()->fromRoute(\'id\');', '', 'if (!$id) {', ' $this->flashMessenger()->addErrorMessage(\'' . $noFoundMessage . '\');', ' ', ' return $this->redirect()->toRoute(\'' . $dashedParam . '\');', '}', '', '$' . $entityParam . ' = $this->' . lcfirst($repositoryClass) . '->getEntityById($id);', '', 'if (!$' . $entityParam . ') {', ' $this->flashMessenger()->addErrorMessage(\'' . $noFoundMessage . '\');', ' ', ' return $this->redirect()->toRoute(\'' . $dashedParam . '\');', '}', '', '$' . $formParam . ' = $this->' . $formParam . ';', '', 'if ($this->params()->fromPost(\'delete_' . $underscoredParam . '\')) {', ' if ($this->' . lcfirst($repositoryClass) . '->removeEntity($' . $entityParam . ')) {', ' $this->flashMessenger()->addSuccessMessage(\'' . $successMessage . '\');', ' ', ' return $this->redirect()->toRoute(\'' . $dashedParam . '\');', ' } else {', ' $this->flashMessenger()->addErrorMessage(\'' . $failedMessage . '\');', ' }', '} else {', ' $this->flashMessenger()->addInfoMessage(\'' . $deleteMessage . '\');', '}', '', '$viewModel = new ViewModel(', ' [', ' \'' . $entityParam . '\' => $' . $entityParam . ',', ' \'' . $formParam . '\' => $' . $formParam . ',', ' ]', ');', '', 'return $viewModel;']; $body = implode(AbstractGenerator::LINE_FEED, $body); $indexAction = new MethodGenerator('indexAction'); $indexAction->addFlag(MethodGenerator::FLAG_PUBLIC); $indexAction->setDocBlock(new DocBlockGenerator('Index action for DeleteController', null, [new ReturnTag(['ViewModel'])])); $indexAction->setBody($body); $this->addMethodFromGenerator($indexAction); }
public function testInvalidArgument() { $this->setExpectedException('PHPUnit_Framework_Error_Notice', 'Undefined index: error'); \Zend\Filter\StaticFilter::execute('error', 'Library\\LogLevel'); }
/** * @return array */ protected function fetchPrimaryColumns() { /** @var ConstraintObject $primaryKey */ $primaryKey = $this->tableData['primaryKey']; $columns = $primaryKey->getColumns(); foreach ($columns as $key => $column) { $columns[$key] = lcfirst(StaticFilter::execute($column, 'Word\\UnderscoreToCamelCase')); } return $columns; }
/** * Convert localized string representations to integer, float or date values * * Subclasses can support localized input formats by calling this method * from a filter. * * Non-string values get trimmed and converted to integer, float or * \DateTime, depending on $type. Invalid values are returned as string. The * input filter should validate filtered data by checking the datatype via * validateType(). * * @param string $value Localized input string * @param string $type Data type (integer, float, date). Any other value will be ignored. * @return mixed Normalized value or input string */ public function normalize($value, $type) { // Integers and floats are validated first to prevent successful parsing // of strings containing invalid characters with the invalid part simply // cut off. switch ($type) { case 'integer': $value = trim($value); if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsInt')) { $value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_INT32)); } break; case 'float': $value = trim($value); if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsFloat')) { $value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_DOUBLE)); } break; case 'date': $value = trim($value); $validator = new \Zend\I18n\Validator\DateTime(); $validator->setDateType(\IntlDateFormatter::SHORT); if ($validator->isValid($value)) { // Some systems accept invalid date separators, like '/' // with a de_DE locale which should accept only '.'. // An extra comparision of the locale-specific pattern and // the input string is necessary. // This also enforces 4-digit years to avoid any confusion // with 2-digit year input. $pattern = preg_quote($validator->getPattern(), '#'); // Get the year part out of the way first. $pattern = preg_replace('/y+/', '§', $pattern); // Remaining letters are placeholders for digits. $pattern = preg_replace('/[a-zA-Z]+/', '\\d+', $pattern); // Set the year pattern. $pattern = str_replace('§', '\\d{4}', $pattern); if (preg_match("#^{$pattern}\$#", $value)) { $formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, 'UTC'); $value = \DateTime::createFromFormat('U', $formatter->parse($value)); } } break; } return $value; }
/** * Generate the create service method * * @param string $className * @param string $moduleName */ protected function addCreateServiceMethod($className, $moduleName) { $managerName = 'inputFilterManager'; // set action body $body = []; $body[] = '$serviceLocator = $' . $managerName . '->getServiceLocator();'; $body[] = ''; /** @var ConstraintObject $foreignKey */ foreach ($this->foreignKeys as $foreignKey) { $storageName = StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase') . 'Storage'; $storageService = $moduleName . '\\' . $this->config['namespaceStorage'] . '\\' . StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase'); $storageParam = lcfirst(StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase')) . 'Storage'; $body[] = '/** @var ' . $storageName . ' $' . $storageParam . ' */'; $body[] = '$' . $storageParam . ' = $serviceLocator->get(\'' . $storageService . '\');'; $body[] = ''; } $body[] = '$instance = new ' . $className . '();'; /** @var ConstraintObject $foreignKey */ foreach ($this->foreignKeys as $foreignKey) { $storageParam = lcfirst(StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase')) . 'Storage'; $setterOption = 'set' . StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase') . 'Options'; $body[] = '$instance->' . $setterOption . '(array_keys($' . $storageParam . '->getOptions()));'; } $body[] = ''; $body[] = 'return $instance;'; $body = implode(AbstractGenerator::LINE_FEED, $body); // create method $method = new MethodGenerator(); $method->setName('createService'); $method->setBody($body); $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]); // check for api docs if ($this->config['flagAddDocBlocks']) { $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])])); } // add method $this->addMethodFromGenerator($method); }
/** * Ensures that if we specify a validator class basename that doesn't * exist in the namespace, get() throws an exception. * * Refactored to conform with ZF-2724. * * @group ZF-2724 */ public function testStaticFactoryClassNotFound() { $this->setExpectedException('Zend\\Loader\\Exception', 'locate class'); StaticFilter::execute('1234', 'UnknownFilter'); }
<?php /** * Display confirmation form for software blacklisting * * Copyright (C) 2011-2016 Holger Schletz <*****@*****.**> * * This program 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 2 of the License, or (at your option) * any later version. * * This program 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 * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ print $this->formYesNo(sprintf($this->translate('Software \'%s\' will be no longer be displayed. Continue?'), $this->escapeHtml(\Zend\Filter\StaticFilter::execute($this->name, 'Library\\FixEncodingErrors'))));
/** * Filter dash to camel case * * @param string $text * * @return string */ public function filterDashToCamelCase($text) { $text = StaticFilter::execute($text, 'Word\\DashToCamelCase'); return $text; }
<?php /** * Display confirmation form for software whitelisting * * Copyright (C) 2011-2016 Holger Schletz <*****@*****.**> * * This program 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 2 of the License, or (at your option) * any later version. * * This program 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 * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ print $this->formYesNo(sprintf($this->translate('Software \'%s\' will be marked as known and accepted. Continue?'), $this->escapeHtml(\Zend\Filter\StaticFilter::execute($this->name, 'Library\\FixEncodingErrors'))));
/** * Save a blog * * @param array $data input data * @param integer $id id of blog entry * @return BlogEntityInterface */ public function save(array $data, $id = null) { // check mode $mode = is_null($id) ? 'create' : 'update'; // get blog entity if ($mode == 'create') { $blog = new BlogEntity(); } else { $blog = $this->fetchSingleById($id); } // get form and set data $form = $this->getForm($mode); $form->setData($data); // check for invalid data if (!$form->isValid()) { $this->setMessage('Bitte Eingaben überprüfen!'); return false; } // get valid blog entity object $blog->exchangeArray($form->getData()); // set values if ($mode == 'create') { $blog->setCdate(date('Y-m-d H:i:s')); } $blog->setUrl(StaticFilter::execute($blog->getTitle(), 'StringToUrl')); // get insert data $saveData = $blog->getArrayCopy(); // save blog try { if ($mode == 'create') { $this->getTable()->insert($saveData); // get last insert value $id = $this->getTable()->getLastInsertValue(); } else { $this->getTable()->update($saveData, array('id' => $id)); } } catch (InvalidQueryException $e) { $this->setMessage('Blogbeitrag wurde nicht gespeichert!'); return false; } // reload blog $blog = $this->fetchSingleById($id); // set success message $this->setMessage('Blogbeitrag wurde gespeichert!'); // return blog return $blog; }
/** * @return array */ protected function fetchTableColumns() { $foreignKeys = []; /** @var ConstraintObject $tableConstraint */ foreach ($this->tableData['foreignKeys'] as $tableConstraint) { $foreignKeys[$tableConstraint->getColumns()[0]] = $tableConstraint->getReferencedTableName(); } $columns = []; /** @var $tableColumn ColumnObject */ foreach ($this->tableData['columns'] as $tableColumn) { if (isset($foreignKeys[$tableColumn->getName()])) { $type = ucfirst($foreignKeys[$tableColumn->getName()]) . 'Entity'; } else { switch ($tableColumn->getDataType()) { case 'varchar': case 'char': case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'enum': case 'set': case 'datetime': case 'timestamp': $type = 'string'; break; case 'decimal': case 'float': case 'double': case 'real': $type = 'float'; break; default: $type = 'integer'; } } $name = lcfirst(StaticFilter::execute($tableColumn->getName(), 'Word\\UnderscoreToCamelCase')); $columns[$name] = $type; } return $columns; }
public function testUsesDifferentConfigurationOnEachRequest() { $first = StaticFilter::execute('foo', 'callback', array('callback' => function ($value) { return 'FOO'; })); $second = StaticFilter::execute('foo', 'callback', array('callback' => function ($value) { return 'BAR'; })); $this->assertNotSame($first, $second); $this->assertEquals('FOO', $first); $this->assertEquals('BAR', $second); }
/** * Filter camel case to underscore * * @param string $text * * @return string */ protected function filterUnderscoreToCamelCase($text) { $text = StaticFilter::execute($text, 'Word\\UnderscoreToCamelCase'); $text = ucfirst($text); return $text; }