コード例 #1
0
 /**
  * Execute after types are built.
  */
 public function postBuild()
 {
     $types_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/types.php" : null;
     if ($types_build_path) {
         $result = [];
         $result[] = '<?php';
         $result[] = '';
         if ($this->getStructure()->getConfig('header_comment')) {
             $result = array_merge($result, explode("\n", $this->getStructure()->getConfig('header_comment')));
             $result[] = '';
         }
         $namespace = $this->getStructure()->getNamespace();
         if ($namespace) {
             $namespace = ltrim($namespace, '\\');
         }
         if ($this->getStructure()->getNamespace()) {
             $result[] = '/**';
             $result[] = ' * @package ' . $this->getStructure()->getNamespace();
             $result[] = ' */';
         }
         $result[] = 'return [';
         foreach ($this->getStructure()->getTypes() as $current_type) {
             $result[] = '    ' . var_export($namespace . '\\' . Inflector::classify(Inflector::singularize($current_type->getName())), true) . ',';
         }
         $result[] = '];';
         $result[] = '';
         $result = implode("\n", $result);
         if (is_file($types_build_path) && file_get_contents($types_build_path) === $result) {
             return;
         } else {
             file_put_contents($types_build_path, $result);
             $this->triggerEvent('on_types_built', [$types_build_path]);
         }
     }
 }
コード例 #2
0
ファイル: Grammar.php プロジェクト: Viacomino/sutra
 /**
  * {@inheritdoc}
  */
 public function camelize($str)
 {
     if (isset($this->rules['camelize'][$str])) {
         return $this->rules['camelize'][$str];
     }
     return DoctrineInflector::classify($str);
 }
コード例 #3
0
 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;
 }
コード例 #4
0
 /**
  * {@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]);
         }
     }
 }
コード例 #5
0
 /**
  * @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;
 }
コード例 #6
0
 /**
  * @param TypeInterface $type
  */
 public function buildType(TypeInterface $type)
 {
     $class_name = Inflector::classify(Inflector::singularize($type->getName()));
     $base_class_name = 'Base\\' . $class_name;
     $class_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/{$class_name}.php" : null;
     if ($class_build_path && is_file($class_build_path)) {
         $this->triggerEvent('on_class_build_skipped', [$class_name, $class_build_path]);
         return;
     }
     $result = [];
     $result[] = '<?php';
     $result[] = '';
     if ($this->getStructure()->getConfig('header_comment')) {
         $result = array_merge($result, explode("\n", $this->getStructure()->getConfig('header_comment')));
         $result[] = '';
     }
     if ($this->getStructure()->getNamespace()) {
         $result[] = 'namespace ' . $this->getStructure()->getNamespace() . ';';
         $result[] = '';
         $result[] = '/**';
         $result[] = ' * @package ' . $this->getStructure()->getNamespace();
         $result[] = ' */';
     }
     $result[] = 'class ' . $class_name . ' extends ' . $base_class_name;
     $result[] = '{';
     $result[] = '}';
     $result[] = '';
     $result = implode("\n", $result);
     if ($this->getBuildPath()) {
         file_put_contents($class_build_path, $result);
     } else {
         eval(ltrim($result, '<?php'));
     }
     $this->triggerEvent('on_class_built', [$class_name, $class_build_path]);
 }
コード例 #7
0
 /**
  * Catch all getter and setter
  *
  * @param  string $name
  * @param  array $arguments
  *
  * @return mixed
  */
 public function __call($name, $arguments)
 {
     // Match the getters
     if (substr($name, 0, 3) == 'get') {
         $parameter = Inflector::tableize(substr($name, 3));
         if (property_exists($this, $parameter)) {
             return $this->{$parameter};
         } else {
             throw new \Exception(sprintf('The property "%s" does not exist.', $parameter));
         }
     }
     // Match the setters
     if (substr($name, 0, 3) == 'set') {
         $parameter = Inflector::tableize(substr($name, 3));
         $method = 'set' . Inflector::classify($parameter);
         if (method_exists($this, $method)) {
             return $this->{$method}($arguments[0]);
         } else {
             if (property_exists($this, $parameter) && isset($arguments[0])) {
                 $this->{$parameter} = $arguments[0];
                 return $this;
             } else {
                 throw new \Exception(sprintf('The property "%s" does not exist.', $parameter));
             }
         }
     }
 }
コード例 #8
0
 /**
  * {@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;
 }
コード例 #9
0
 /**
  * @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();
 }
コード例 #10
0
 public function addTest($testName)
 {
     $methodName = 'test' . Inflector::classify($testName);
     $testMethod = new ClassMethod($methodName, array(), array());
     $testMethod->setScope('public');
     $this->methods[] = $testMethod;
     return $testMethod;
 }
コード例 #11
0
 /**
  * Create platform function node.
  *
  * @param string $platformName
  * @param string $functionName
  * @param array $parameters
  * @throws \Doctrine\ORM\Query\QueryException
  * @return PlatformFunctionNode
  */
 public static function create($platformName, $functionName, array $parameters)
 {
     $className = __NAMESPACE__ . '\\Platform\\Functions\\' . Inflector::classify(strtolower($platformName)) . '\\' . Inflector::classify(strtolower($functionName));
     if (!class_exists($className)) {
         throw QueryException::syntaxError(sprintf('Function "%s" does not supported for platform "%s"', $functionName, $platformName));
     }
     return new $className($parameters);
 }
コード例 #12
0
 /**
  * Parse a response body into a collection
  *
  * @param  string $data
  *
  * @return ResultCollection
  */
 public static function parseResult($data)
 {
     $responseBody = json_decode($data, true);
     $rootKey = self::getRootKey($responseBody);
     $data = self::getResultForRootKey($responseBody, $rootKey);
     $className = Inflector::classify($rootKey);
     $result = new Result();
     return $result->fromArrayWithObject($data, $className);
 }
コード例 #13
0
ファイル: SetInstantiator.php プロジェクト: ferodss/input
 public function instantiate(string $class, array $data)
 {
     $object = new $class();
     foreach ($data as $key => $value) {
         $method = 'set' . Inflector::classify($key);
         $object->{$method}($value);
     }
     return $object;
 }
コード例 #14
0
ファイル: Factory.php プロジェクト: code-community/input
 public function getHandler($alias)
 {
     $className = Inflector::classify($alias);
     $handlerClass = sprintf('\\%s\\%sHandler', $this->handlerNamespace, $className);
     if (!class_exists($handlerClass)) {
         throw new \RuntimeException('The specified handler class does not exist: ' . $handlerClass);
     }
     return new $handlerClass($this->typeHandler);
 }
コード例 #15
0
 /**
  * @param string $controller
  * @return string
  */
 public static function getActionClassFromControllerName($controller)
 {
     $actionNameStart = strpos($controller, ':') + 1;
     $actionNameLength = strrpos($controller, 'Action') - $actionNameStart;
     $actionName = substr($controller, $actionNameStart, $actionNameLength);
     $actionName = Inflector::classify($actionName);
     $refl = new \ReflectionClass(Action::class);
     return $refl->getNamespaceName() . '\\' . $actionName;
 }
コード例 #16
0
ファイル: ModuleTrait.php プロジェクト: vvval/spiral
 /**
  * @param string $module
  * @return string
  */
 public function guessClass($module)
 {
     $module = str_replace('/', '\\', $module);
     $module = explode('\\', $module);
     array_walk($module, function (&$chunk) {
         $chunk = Inflector::classify($chunk);
     });
     return join('\\', $module) . 'Module';
 }
コード例 #17
0
ファイル: ListManager.php プロジェクト: bravo3/orm
 /**
  * Resolve default setter/getter names
  *
  * @param string $property
  * @param string $getter
  * @param string $setter
  * @return string[]
  */
 protected static function resolveFunctionNames($property, $getter = null, $setter = null)
 {
     if (!$getter) {
         $getter = 'get' . Inflector::classify($property);
     }
     if (!$setter) {
         $setter = 'set' . Inflector::classify($property);
     }
     return [$getter, $setter];
 }
コード例 #18
0
 /**
  * @param TypeInterface $type
  */
 public function buildType(TypeInterface $type)
 {
     $base_manager_class_name = Inflector::classify($type->getName());
     $type_class_name = Inflector::classify(Inflector::singularize($type->getName()));
     $base_class_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/Manager/Base/{$base_manager_class_name}.php" : null;
     $result = [];
     $result[] = '<?php';
     $result[] = '';
     if ($this->getStructure()->getConfig('header_comment')) {
         $result = array_merge($result, explode("\n", $this->getStructure()->getConfig('header_comment')));
         $result[] = '';
     }
     if ($this->getStructure()->getNamespace()) {
         $base_class_namespace = $this->getStructure()->getNamespace() . '\\Manager\\Base';
         $type_class_name = '\\' . ltrim($this->getStructure()->getNamespace(), '\\') . '\\' . $type_class_name;
     } else {
         $base_class_namespace = 'Manager\\Base';
     }
     $result[] = 'namespace ' . $base_class_namespace . ';';
     $result[] = '';
     $result[] = '/**';
     $result[] = ' * @package ' . $base_class_namespace;
     $result[] = ' */';
     $interfaces = $traits = [];
     foreach ($type->getTraits() as $interface => $implementations) {
         if ($interface != '--just-paste-trait--') {
             $interfaces[] = '\\' . ltrim($interface, '\\');
         }
         if (count($implementations)) {
             foreach ($implementations as $implementation) {
                 $traits[] = '\\' . ltrim($implementation, '\\');
             }
         }
     }
     $result[] = 'abstract class ' . $base_manager_class_name . ' extends \\ActiveCollab\\DatabaseObject\\Entity\\Manager';
     $result[] = '{';
     $result[] = '    /**';
     $result[] = '     * Return type that this manager works with.';
     $result[] = '     *';
     $result[] = '     * @return string';
     $result[] = '     */';
     $result[] = '    public function getType()';
     $result[] = '    {';
     $result[] = '        return ' . var_export($type_class_name, true) . ';';
     $result[] = '    }';
     $result[] = '}';
     $result[] = '';
     $result = implode("\n", $result);
     if ($this->getBuildPath()) {
         file_put_contents($base_class_build_path, $result);
     } else {
         eval(ltrim($result, '<?php'));
     }
     $this->triggerEvent('on_class_built', [$base_manager_class_name, $base_class_build_path]);
 }
コード例 #19
0
ファイル: ClientGenerator.php プロジェクト: stof/jane-swagger
 protected function generateClass($group, $operations, $namespace, Context $context, $suffix = 'Resource')
 {
     $factory = new BuilderFactory();
     $name = $group === 0 ? '' : $group;
     $class = $factory->class(Inflector::classify($name . $suffix));
     $class->extend('Resource');
     foreach ($operations as $operation) {
         $class->addStmt($this->operationGenerator->generate($this->operationNaming->generateFunctionName($operation), $operation, $context));
     }
     return $factory->namespace($namespace . "\\Resource")->addStmt($factory->use('Joli\\Jane\\Swagger\\Client\\QueryParam'))->addStmt($factory->use('Joli\\Jane\\Swagger\\Client\\Resource'))->addStmt($class)->getNode();
 }
コード例 #20
0
 /**
  * Set object properties.
  */
 public function setObjectProperties($object, $properties)
 {
     foreach ($properties as $key => $value) {
         $method = sprintf('set%s', Inflector::classify($key));
         if (false === method_exists($object, $method)) {
             continue;
         }
         $object->{$method}($value);
     }
     return $object;
 }
コード例 #21
0
 /**
  * {@inheritdoc}
  */
 public function generateFromClassname($classname)
 {
     $bundles = $this->kernel->getBundles();
     foreach ($bundles as $bundle) {
         if (0 !== strpos($classname, $bundle->getNamespace())) {
             continue;
         }
         $classname = sprintf('%s\\%s', Inflector::classify($bundle->getName()), trim(substr($classname, strlen($bundle->getNamespace())), '\\'));
     }
     return $this->generator->generateFromClassname($classname);
 }
コード例 #22
0
ファイル: AbstractGenerator.php プロジェクト: jwdeitch/spiral
 /**
  * Set class name, name must not include default namespace and postfix.
  *
  * @param string $name
  * @return $this
  */
 public function setName($name)
 {
     if (strpos($name, '/') !== false || strpos($name, '\\') !== false) {
         $name = str_replace('/', '\\', $name);
         //Let's split namespace
         $this->setNamespace(substr($name, 0, strrpos($name, '\\')));
         $name = substr($name, strrpos($name, '\\') + 1);
     }
     $this->class->setName(Inflector::classify($name) . $this->options['postfix']);
     return $this;
 }
コード例 #23
0
ファイル: Reactor.php プロジェクト: jwdeitch/spiral
 /**
  * Find full class name using it's configured type and short name. Reaction will automatically
  * add namespace and postfix. Method will return null if class can not be found.
  *
  * @param string $type
  * @param string $name
  * @return string|null
  * @throws ReactorException
  */
 public function findClass($type, $name)
 {
     if (!isset($this->config['generators'][$type])) {
         throw new ReactorException("Undefined class type '{$type}'.");
     }
     $definition = $this->config['generators'][$type];
     $class = $definition['namespace'] . '\\' . Inflector::classify($name) . $definition['postfix'];
     if (!class_exists($class)) {
         return null;
     }
     return $class;
 }
コード例 #24
0
 /**
  * Get a supported metric as a property.
  *
  * @param  string          $metric
  * @return MetricInterface
  */
 public function __get($metric)
 {
     if (empty($this->metrics[$metric])) {
         $class_name = '\\ActiveCollab\\Insight\\AccountInsight\\Metric\\' . Inflector::classify($metric);
         if (class_exists($class_name)) {
             $this->metrics[$metric] = new $class_name($this, $this->insight, $this->connection, $this->log);
         } else {
             throw new LogicException("Metric '{$metric}' is not currently supported");
         }
     }
     return $this->metrics[$metric];
 }
コード例 #25
0
 /**
  * @param string $element
  * @param string $name
  * @return string
  */
 public function elementNamespace($element, $name = '')
 {
     $localNamespace = trim($this->elementOption($element, 'namespace', ''), '\\');
     list($namespace, $name) = $this->splitName($name);
     if (!empty($namespace)) {
         $localNamespace .= '\\' . Inflector::classify($namespace);
     }
     if (empty($this->baseNamespace())) {
         return $localNamespace;
     }
     return trim($this->baseNamespace() . '\\' . $localNamespace, '\\');
 }
 protected function getFieldMethods($model, $field_name)
 {
     $camelizedFieldName = Inflector::classify($field_name);
     $methods = array('getters' => array("get{$camelizedFieldName}", "is{$camelizedFieldName}"), 'setters' => array("set{$camelizedFieldName}"));
     foreach ($methods as $type => $type_methods) {
         foreach ($type_methods as $i => $method) {
             if (!method_exists($model, $method)) {
                 unset($methods[$type][$i]);
             }
         }
     }
     return $methods;
 }
コード例 #27
0
 protected function resolveController($parameters)
 {
     if ($parameters['_route'] === 'magic') {
         // Controller is not defined, magically resolve.
         $controller = sprintf('Eng\\%s\\Controller\\%sController::%sAction', $this->bundle, Inflector::classify(strtolower($parameters['controller'])), Inflector::camelize(strtolower($parameters['action'])));
     } else {
         // Controller to use defined explicitly in route parameters
         $controller = $parameters['_controller'];
     }
     list($controller, $action) = $this->createController($controller);
     if (!method_exists($controller, $action)) {
         throw new \InvalidArgumentException(sprintf('Method "%s::%s" does not exist.', get_class($controller), $action));
     }
     return array($controller, $action);
 }
コード例 #28
0
 /**
  * @param ApiResource $apiResource
  */
 protected function addActions(ApiResource $apiResource)
 {
     $options = $this->getOptionsForApiResource($apiResource);
     $def = $this->getDefinitionForApiResource($apiResource);
     foreach ($this->getActionsForApiResource($apiResource) as $actionName) {
         $class = Inflector::classify($actionName);
         $actionClass = "BiteCodes\\RestApiGeneratorBundle\\Api\\Actions\\{$class}";
         $action = new Definition($actionClass);
         $action->addArgument(new Reference('router'));
         $action->addMethodCall('setSecurityExpression', [$options['routes'][$actionName]['security']]);
         $action->addMethodCall('setSerializationGroups', [$options['routes'][$actionName]['serialization_groups']]);
         $this->container->set('bite_codes.rest_api_generator.action.' . $apiResource->getName() . '.' . Inflector::tableize($actionName), $action);
         $def->addMethodCall('addAction', [$action]);
     }
 }
コード例 #29
0
 public function arrayToObject($hookData)
 {
     if (is_array($hookData) && count($hookData)) {
         $hook = new Duration();
         foreach ($hookData as $property => $value) {
             // TODO: Research whether this is a security risk, e.g. if the property name has been injected via a REST post.
             $method = 'set' . Inflector::classify($property);
             if (($method == 'setStartDate' || $method == 'setEndDate') && !is_object($value) && !$value instanceof \DateTime) {
                 $value = new \DateTime($value, new \DateTimeZone($hookData['timezone']));
             }
             $hook->{$method}($value);
         }
     }
     return $hook;
 }
コード例 #30
0
 public function arrayToObject($hookData)
 {
     if (is_array($hookData) && count($hookData)) {
         $hook = new Assignee();
         foreach ($hookData as $property => $value) {
             // TODO: Research whether this is a security risk, e.g. if the property name has been injected via a REST post.
             $method = (string) 'set' . Inflector::classify($property);
             if ($method == 'setUser' && !is_object($value)) {
                 $value = $this->em->getRepository('CampaignChainCoreBundle:User')->find($value);
             }
             $hook->{$method}($value);
         }
     }
     return $hook;
 }