本文整理汇总了PHP中Doctrine\Common\Inflector\Inflector类的典型用法代码示例。如果您正苦于以下问题:PHP Inflector类的具体用法?PHP Inflector怎么用?PHP Inflector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Inflector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getName
public function getName()
{
$name = $this->reflection->getName();
$inflector = new Inflector();
$name = $inflector->tableize($name);
return $name;
}
示例2: validate
public function validate(Request $request, array $rules)
{
$valid = true;
foreach ($rules as $field => $rule) {
if (is_null($rule) || !is_string($rule) || strlen($rule) == 0) {
throw new ValidationException("Rule must be a string");
}
// get field value
$value = $request->input($field);
// split validation rule into required / sometimes (no validation if not set or empty)
// contract and contract parameters
$parts = explode("|", $rule);
if (is_null($parts) || !is_array($parts) || count($parts) < 3) {
throw new ValidationException("Invalid rule");
}
$required = strtolower($parts[0]) == "required" ? true : false;
if ($required && is_null($value)) {
$valid = false;
continue;
}
$args = explode(":", $parts[1]);
$clazz = Inflector::classify($args[0]) . "Contract";
if (!class_exists($clazz)) {
throw new ValidationException("Invalid rule: invalid validation class '{$clazz}'");
}
$instance = new $clazz($value, isset($args[1]) ? $args[1] : array());
if (!$instance instanceof Contract) {
throw new ValidationException("Invalid rule: invalid validation class '{$clazz}'. Class must extend Simplified\\Validator\\Contract");
}
if (!$instance->isValid()) {
$valid = false;
}
}
return $valid;
}
示例3: prePersist
/**
* @param LifecycleEventArgs $event
*/
public function prePersist(LifecycleEventArgs $event)
{
$document = $event->getDocument();
$className = get_class($document);
$generateAnnotations = $this->annotationReader->getClassAnnotation(new \ReflectionClass($className), 'OpenOrchestra\\Mapping\\Annotations\\Document');
if (!is_null($generateAnnotations)) {
$repository = $this->container->get($generateAnnotations->getServiceName());
$getSource = $generateAnnotations->getSource($document);
$getGenerated = $generateAnnotations->getGenerated($document);
$setGenerated = $generateAnnotations->setGenerated($document);
$testMethod = $generateAnnotations->getTestMethod();
if ($testMethod === null && $repository instanceof FieldAutoGenerableRepositoryInterface) {
$testMethod = 'testUniquenessInContext';
}
if (is_null($document->{$getGenerated}())) {
$source = $document->{$getSource}();
$source = Inflector::tableize($source);
$sourceField = $this->suppressSpecialCharacterHelper->transform($source);
$generatedField = $sourceField;
$count = 1;
while ($repository->{$testMethod}($generatedField)) {
$generatedField = $sourceField . '-' . $count;
$count++;
}
$document->{$setGenerated}($generatedField);
}
}
}
示例4: getDirection
/**
* {@inheritdoc}
*/
public function getDirection($activity, $target)
{
//check if target is entity created from admin part
if (!$target instanceof EmailHolderInterface) {
$metadata = $this->doctrineHelper->getEntityMetadata($target);
$columns = $metadata->getColumnNames();
$className = get_class($target);
foreach ($columns as $column) {
//check only columns with 'contact_information'
if ($this->isEmailType($className, $column)) {
$getMethodName = "get" . Inflector::classify($column);
/** @var $activity Email */
if ($activity->getFromEmailAddress()->getEmail() === $target->{$getMethodName}()) {
return DirectionProviderInterface::DIRECTION_OUTGOING;
} else {
foreach ($activity->getTo() as $recipient) {
if ($recipient->getEmailAddress()->getEmail() === $target->{$getMethodName}()) {
return DirectionProviderInterface::DIRECTION_INCOMING;
}
}
}
}
}
return DirectionProviderInterface::DIRECTION_UNKNOWN;
}
/** @var $activity Email */
/** @var $target EmailHolderInterface */
if ($activity->getFromEmailAddress()->getEmail() === $target->getEmail()) {
return DirectionProviderInterface::DIRECTION_OUTGOING;
}
return DirectionProviderInterface::DIRECTION_INCOMING;
}
示例5: process
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$reader = $container->get('annotation_reader');
$registry = $container->getDefinition('lemon_rest.object_registry');
foreach ($bundles as $name => $bundle) {
$reflection = new \ReflectionClass($bundle);
$baseNamespace = $reflection->getNamespaceName() . '\\Entity\\';
$dir = dirname($reflection->getFileName()) . '/Entity';
if (is_dir($dir)) {
$finder = new Finder();
$iterator = $finder->files()->name('*.php')->in($dir);
/** @var SplFileInfo $file */
foreach ($iterator as $file) {
// Translate the directory path from our starting namespace forward
$expandedNamespace = substr($file->getPath(), strlen($dir) + 1);
// If we are in a sub namespace add a trailing separation
$expandedNamespace = $expandedNamespace === false ? '' : $expandedNamespace . '\\';
$className = $baseNamespace . $expandedNamespace . $file->getBasename('.php');
if (class_exists($className)) {
$reflectionClass = new \ReflectionClass($className);
foreach ($reader->getClassAnnotations($reflectionClass) as $annotation) {
if ($annotation instanceof Resource) {
$name = $annotation->name ?: Inflector::pluralize(lcfirst($reflectionClass->getShortName()));
$definition = new Definition('Lemon\\RestBundle\\Object\\Definition', array($name, $className, $annotation->search, $annotation->create, $annotation->update, $annotation->delete, $annotation->partialUpdate));
$container->setDefinition('lemon_rest.object_resources.' . $name, $definition);
$registry->addMethodCall('add', array($definition));
}
}
}
}
}
}
}
示例6: toIdentifier
private function toIdentifier($object)
{
$className = get_class($object);
$className = substr($className, strrpos($className, '\\') + 1);
$className = str_replace('SystemInfo', '', $className);
return Inflector::tableize($className);
}
示例7: postPersist
public function postPersist(LifecycleEventArgs $event)
{
/** @var OroEntityManager $em */
$em = $event->getEntityManager();
$entity = $event->getEntity();
$configProvider = $em->getExtendManager()->getConfigProvider();
$className = get_class($entity);
if ($configProvider->hasConfig($className)) {
$config = $configProvider->getConfig($className);
$schema = $config->get('schema');
if (isset($schema['relation'])) {
foreach ($schema['relation'] as $fieldName) {
/** @var Config $fieldConfig */
$fieldConfig = $configProvider->getConfig($className, $fieldName);
if ($fieldConfig->getId()->getFieldType() == 'optionSet' && ($setData = $entity->{Inflector::camelize('get_' . $fieldName)}())) {
$model = $configProvider->getConfigManager()->getConfigFieldModel($fieldConfig->getId()->getClassName(), $fieldConfig->getId()->getFieldName());
/**
* in case of single select field type, should wrap value in array
*/
if ($setData && !is_array($setData)) {
$setData = [$setData];
}
foreach ($setData as $option) {
$optionSetRelation = new OptionSetRelation();
$optionSetRelation->setData(null, $entity->getId(), $model, $em->getRepository(OptionSet::ENTITY_NAME)->find($option));
$em->persist($optionSetRelation);
$this->needFlush = true;
}
}
}
}
}
}
示例8: theFollowingEntitiesExist
/**
* @Given the following :entityName entities exist:
*/
public function theFollowingEntitiesExist($entityName, TableNode $table)
{
/** @var EntityManager $doctrine */
$doctrine = $this->get('doctrine')->getManager();
$meta = $doctrine->getClassMetadata($entityName);
$rows = [];
$hash = $table->getHash();
foreach ($hash as $row) {
$id = $row['id'];
unset($row['id']);
foreach ($row as $property => &$value) {
$propertyName = Inflector::camelize($property);
$fieldType = $meta->getTypeOfField($propertyName);
switch ($fieldType) {
case 'array':
case 'json_array':
$value = json_decode($value, true);
break;
case 'datetime':
$value = new \DateTime($value);
break;
}
}
$rows[$id] = $row;
}
$this->persistEntities($entityName, $rows);
}
示例9: getParametersFromObject
/**
* @param $keys
* @param $object
* @return array
*/
protected function getParametersFromObject($keys, $object)
{
$parameters = [];
foreach ($keys as $key) {
$relation = $object;
$method = 'get' . Inflector::classify($key);
if (method_exists($relation, $method)) {
$relation = $relation->{$method}();
} else {
$segments = explode('_', $key);
if (count($segments) > 1) {
foreach ($segments as $segment) {
$method = 'get' . Inflector::classify($segment);
if (method_exists($relation, $method)) {
$relation = $relation->{$method}();
} else {
$relation = $object;
break;
}
}
}
}
if ($object !== $relation) {
$parameters[$key] = $relation;
}
}
return $parameters;
}
示例10: fromArray
/**
* @param array $data
*/
public function fromArray(array $data)
{
foreach ($data as $key => $value) {
$property = Inflector::camelize($key);
$this->{$property} = $value;
}
}
示例11: transform
public function transform($entities)
{
foreach ($entities as &$entity) {
$entity['icon'] = $this->getIcon(Inflector::singularize($entity['name']));
}
return $entities;
}
示例12: reverseTransform
/**
* @param Request $request
* @param string $id
* @param string $type
* @param string $event
* @param string $eventClass
*
* @return Response
*/
protected function reverseTransform(Request $request, $id, $type, $event, $eventClass)
{
$facadeName = Inflector::classify($type) . 'Facade';
$typeName = Inflector::tableize($type);
$format = $request->get('_format', 'json');
$facade = $this->get('jms_serializer')->deserialize($request->getContent(), 'OpenOrchestra\\ApiBundle\\Facade\\' . $facadeName, $format);
$mixed = $this->get('open_orchestra_model.repository.' . $typeName)->find($id);
$oldStatus = null;
if ($mixed instanceof StatusableInterface) {
$oldStatus = $mixed->getStatus();
}
$mixed = $this->get('open_orchestra_api.transformer_manager')->get($typeName)->reverseTransform($facade, $mixed);
if ($this->isValid($mixed)) {
$em = $this->get('object_manager');
$em->persist($mixed);
$em->flush();
if (in_array('OpenOrchestra\\ModelInterface\\Event\\EventTrait\\EventStatusableInterface', class_implements($eventClass))) {
$this->dispatchEvent($event, new $eventClass($mixed, $oldStatus));
return array();
}
$this->dispatchEvent($event, new $eventClass($mixed));
return array();
}
return $this->getViolations();
}
示例13: invoke
/**
* @param FactoryArguments $arguments
* @param $method
* @param array $parameters
* @return mixed
* @throws \LukaszMordawski\CampaignMonitorBundle\Exception\Exception
* @throws \LogicException
*
* This method invokes proper API method and stores result in cache.
*/
public function invoke(FactoryArguments $arguments, $method, $parameters = [])
{
if (!$arguments->clientId) {
$arguments->clientId = $this->clientId;
}
$method = Inflector::tableize($method);
$cacheKey = $this->getCacheKey($arguments, $method, $parameters);
if ($this->cache->contains($cacheKey)) {
return unserialize($this->cache->fetch($cacheKey));
}
$csClient = $this->factory->factory($arguments);
if (method_exists($csClient, $method)) {
if (is_array($parameters)) {
$data = call_user_func_array([$csClient, $method], $parameters);
} else {
$data = call_user_func([$csClient, $method], $parameters);
}
} else {
throw new \LogicException(sprintf('Method %s does not exist for class %s', $method, get_class($csClient)));
}
if ($data->http_status_code != 200 && $data->http_status_code != 201) {
throw new Exception($data->response->Message, $data->response->Code);
}
$this->cache->save($cacheKey, serialize($data->response), $this->cacheLifetime);
return $data->response;
}
示例14: arrayToXml
public static function arrayToXml(array $data, \SimpleXMLElement $xml, $parentKey = null, $keyFilterCallback = null)
{
foreach ($data as $k => $v) {
if (!is_numeric($k) && is_callable($keyFilterCallback)) {
$k = call_user_func($keyFilterCallback, $k);
}
if (is_array($v)) {
if (!is_numeric($k)) {
self::arrayToXml($v, $xml->addChild($k), $k, $keyFilterCallback);
} else {
self::arrayToXml($v, $xml->addChild(Inflector::singularize($parentKey)), null, $keyFilterCallback);
}
} else {
if (!is_numeric($k)) {
$xml->addChildWithCDATA($k, $v);
} else {
if (!is_null($parentKey)) {
$xml->addChildWithCDATA(Inflector::singularize($parentKey), $v);
} else {
throw new \Exception("Array To xml forma error: invalid element name {$k}");
}
}
}
}
return $xml;
}
示例15: process
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition(self::SERVICE_KEY)) {
return;
}
// find providers
$providers = [];
$taggedServices = $container->findTaggedServiceIds(self::TAG);
foreach ($taggedServices as $id => $attributes) {
if (empty($attributes[0]['scope'])) {
throw new InvalidConfigurationException(sprintf('Tag attribute "scope" is required for "%s" service', $id));
}
$priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
$scope = $attributes[0]['scope'];
$providers[$scope][$priority][] = new Reference($id);
}
if (empty($providers)) {
return;
}
// add to chain
$serviceDef = $container->getDefinition(self::SERVICE_KEY);
foreach ($providers as $scope => $items) {
// sort by priority and flatten
krsort($items);
$items = call_user_func_array('array_merge', $items);
// register
foreach ($items as $provider) {
$serviceDef->addMethodCall(sprintf('add%sVariablesProvider', Inflector::classify($scope)), [$provider]);
}
}
}