Example #1
1
 /**
  * Returns information about this extension plugin
  *
  * @param array $params Parameters to the hook
  *
  * @return string Information about pi1 plugin
  * @hook TYPO3_CONF_VARS|SC_OPTIONS|cms/layout/class.tx_cms_layout.php|list_type_Info|calendarize_calendar
  */
 public function getExtensionSummary(array $params)
 {
     $relIconPath = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . ExtensionManagementUtility::siteRelPath('calendarize') . 'ext_icon.png';
     $this->flexFormService = GeneralUtility::makeInstance('HDNET\\Calendarize\\Service\\FlexFormService');
     $this->layoutService = GeneralUtility::makeInstance('HDNET\\Calendarize\\Service\\ContentElementLayoutService');
     $this->layoutService->setTitle('<img src="' . $relIconPath . '" /> Calendarize');
     if ($params['row']['list_type'] != 'calendarize_calendar') {
         return '';
     }
     $this->flexFormService->load($params['row']['pi_flexform']);
     if (!$this->flexFormService->isValid()) {
         return '';
     }
     $actions = $this->flexFormService->get('switchableControllerActions', 'main');
     $parts = GeneralUtility::trimExplode(';', $actions, true);
     $parts = array_map(function ($element) {
         $split = explode('->', $element);
         return ucfirst($split[1]);
     }, $parts);
     $actionKey = lcfirst(implode('', $parts));
     $this->layoutService->addRow(LocalizationUtility::translate('mode', 'calendarize'), LocalizationUtility::translate('mode.' . $actionKey, 'calendarize'));
     $this->layoutService->addRow(LocalizationUtility::translate('configuration', 'calendarize'), $this->flexFormService->get('settings.configuration', 'main'));
     if ((bool) $this->flexFormService->get('settings.hidePagination', 'main')) {
         $this->layoutService->addRow(LocalizationUtility::translate('hide.pagination.teaser', 'calendarize'), '!!!');
     }
     $this->addPageIdsToTable();
     return $this->layoutService->render();
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     // Prepare variables
     $table = lcfirst($this->option('table'));
     $viewVars = compact('table');
     // Prompt
     $this->line('');
     $this->info("Table name: {$table}");
     $this->comment("A migration that creates social_sites and user_social_sites tables," . " referencing the {$table} table will" . " be created in app/database/migrations directory");
     $this->line('');
     if ($this->confirm("Proceed with the migration creation? [Yes|no]")) {
         $this->info("Creating migration...");
         // Generate
         $filename = 'database/migrations/' . date('Y_m_d_His') . "_create_oauth_client_setup_tables.php";
         $output = $this->app['view']->make('laravel-oauth-client::generators.migration', $viewVars)->render();
         $filename = $this->app['path'] . '/' . trim($filename, '/');
         $directory = dirname($filename);
         if (!is_dir($directory)) {
             @mkdir($directory, 0755, true);
         }
         @file_put_contents($filename, $output, FILE_APPEND);
         $this->info("Migration successfully created!");
     }
     $this->call('dump-autoload');
 }
Example #3
0
 public static function camelCase($str, $exclude = array())
 {
     $str = preg_replace('/[^a-z0-9' . implode('', $exclude) . ']+/i', ' ', $str);
     // uppercase the first character of each word
     $str = ucwords(trim($str));
     return lcfirst(str_replace(' ', '', $str));
 }
Example #4
0
 /**
  * Generate a list of routes available fo the specified method.
  *
  * @param ReflectionMethod $methodReflection
  * @return array
  */
 public function generateRestRoutes(ReflectionMethod $methodReflection)
 {
     $routes = array();
     $routePath = "/:" . Mage_Webapi_Controller_Router_Route_Rest::PARAM_VERSION;
     $routeParts = $this->_helper->getResourceNameParts($methodReflection->getDeclaringClass()->getName());
     $partsCount = count($routeParts);
     for ($i = 0; $i < $partsCount; $i++) {
         if ($this->_isParentResourceIdExpected($methodReflection) && $i == $partsCount - 1) {
             $routePath .= "/:" . Mage_Webapi_Controller_Router_Route_Rest::PARAM_PARENT_ID;
         }
         $routePath .= "/" . lcfirst($this->_helper->convertSingularToPlural($routeParts[$i]));
     }
     if ($this->_isResourceIdExpected($methodReflection)) {
         $routePath .= "/:" . Mage_Webapi_Controller_Router_Route_Rest::PARAM_ID;
     }
     foreach ($this->_getAdditionalRequiredParamNames($methodReflection) as $additionalRequired) {
         $routePath .= "/{$additionalRequired}/:{$additionalRequired}";
     }
     $actionType = Mage_Webapi_Controller_Request_Rest::getActionTypeByOperation($this->_helper->getMethodNameWithoutVersionSuffix($methodReflection));
     $resourceName = $this->_helper->translateResourceName($methodReflection->getDeclaringClass()->getName());
     $optionalParams = $this->_getOptionalParamNames($methodReflection);
     foreach ($this->_getPathCombinations($optionalParams, $routePath) as $finalRoutePath) {
         $routes[$finalRoutePath] = array('actionType' => $actionType, 'resourceName' => $resourceName);
     }
     $this->_routes = array_merge($this->_routes, $routes);
     return $routes;
 }
 /**
  * Generate the CRUD controller.
  *
  * @param BundleInterface   $bundle           A bundle object
  * @param string            $entity           The entity relative class name
  * @param ClassMetadataInfo $metadata         The entity class metadata
  * @param string            $format           The configuration format (xml, yaml, annotation)
  * @param string            $routePrefix      The route name prefix
  * @param array             $needWriteActions Wether or not to generate write actions
  *
  * @throws \RuntimeException
  */
 public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $format, $routePrefix, $needWriteActions, $forceOverwrite)
 {
     $this->routePrefix = $routePrefix;
     $this->routeNamePrefix = self::getRouteNamePrefix($routePrefix);
     $this->actions = $needWriteActions ? array('index', 'show', 'new', 'edit', 'delete') : array('index', 'show');
     if (count($metadata->identifier) != 1) {
         throw new \RuntimeException('The CRUD generator does not support entity classes with multiple or no primary keys.');
     }
     $this->entity = $entity;
     $this->entitySingularized = lcfirst(Inflector::singularize($entity));
     $this->entityPluralized = lcfirst(Inflector::pluralize($entity));
     $this->bundle = $bundle;
     $this->metadata = $metadata;
     $this->setFormat($format);
     $this->generateControllerClass($forceOverwrite);
     $dir = sprintf('%s/Resources/views/%s', $this->rootDir, str_replace('\\', '/', strtolower($this->entity)));
     if (!file_exists($dir)) {
         $this->filesystem->mkdir($dir, 0777);
     }
     $this->generateIndexView($dir);
     if (in_array('show', $this->actions)) {
         $this->generateShowView($dir);
     }
     if (in_array('new', $this->actions)) {
         $this->generateNewView($dir);
     }
     if (in_array('edit', $this->actions)) {
         $this->generateEditView($dir);
     }
     $this->generateTestClass();
     $this->generateConfiguration();
 }
 /**
  * Generate view content
  *
  * @param string          $moduleName
  * @param ClassReflection $loadedEntity
  */
 protected function addContent($moduleName, ClassReflection $loadedEntity)
 {
     // prepare some params
     $moduleIdentifier = $this->filterCamelCaseToUnderscore($moduleName);
     $entityName = $loadedEntity->getShortName();
     $entityParam = lcfirst($entityName);
     $formParam = lcfirst(str_replace('Entity', '', $loadedEntity->getShortName())) . 'DataForm';
     $moduleRoute = $this->filterCamelCaseToDash($moduleName);
     // set action body
     $body = [];
     $body[] = 'use ' . $loadedEntity->getName() . ';';
     $body[] = '';
     $body[] = '/** @var ' . $entityName . ' $' . $entityParam . ' */';
     $body[] = '$' . $entityParam . ' = $this->' . $entityParam . ';';
     $body[] = '';
     $body[] = '$this->h1(\'' . $moduleIdentifier . '_title_update\');';
     $body[] = '';
     $body[] = '$this->' . $formParam . '->setAttribute(\'action\', $this->url(\'' . $moduleRoute . '/update\', [\'id\' => $' . $entityParam . '->getIdentifier()]));';
     $body[] = '';
     $body[] = 'echo $this->bootstrapForm($this->' . $formParam . ');';
     $body[] = '?>';
     $body[] = '<p>';
     $body[] = '    <a class="btn btn-primary" href="<?php echo $this->url(\'' . $moduleRoute . '\'); ?>">';
     $body[] = '        <i class="fa fa-table"></i>';
     $body[] = '        <?php echo $this->translate(\'' . $moduleIdentifier . '_action_index\'); ?>';
     $body[] = '    </a>';
     $body[] = '</p>';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // add method
     $this->setContent($body);
 }
/**
 * Rewrites CI's timespan function
 * Leaving only years and months
 * @param int $seconds Number of Seconds
 * @param string $time Unix Timestamp
 * @return string String representaton of date difference
 */
function timespan($seconds = 1, $time = '')
{
    $CI =& get_instance();
    $CI->lang->load('date');
    if (!is_numeric($seconds)) {
        $seconds = 1;
    }
    if (!is_numeric($time)) {
        $time = time();
    }
    if ($time <= $seconds) {
        $seconds = 1;
    } else {
        $seconds = $time - $seconds;
    }
    $str = '';
    $years = floor($seconds / 31536000);
    if ($years > 0) {
        $str .= $years . ' ' . lcfirst($CI->lang->line($years > 1 ? 'date_years' : 'date_year')) . ', ';
    }
    $seconds -= $years * 31536000;
    $months = floor($seconds / 2628000);
    if ($years > 0 or $months > 0) {
        if ($months > 0) {
            $str .= $months . ' ' . lcfirst($CI->lang->line($months > 1 ? 'date_months' : 'date_month')) . ', ';
        }
    }
    return substr(trim($str), 0, -1);
}
Example #8
0
 /**
  * Get our comparison data by scanning our comparison directory
  * @return array
  */
 public function toJson()
 {
     // Add our current directory pointer to the array (can't be done in property definition)
     array_unshift($this->comparisonDir, dirname(__FILE__));
     // Try to do this platform independent
     $comparisonDir = implode(DIRECTORY_SEPARATOR, $this->comparisonDir);
     if (!count($this->comparisonCache)) {
         // Iterate our directory looking for comparison classes
         foreach (new DirectoryIterator($comparisonDir) as $file) {
             // Skip sub-dirs and dot files
             if ($file->isDir() || $file->isDot()) {
                 continue;
             }
             $fileName = $file->getFilename();
             $className = str_replace('.php', '', $fileName);
             $reflectClass = new ReflectionClass('\\Verdict\\Filter\\Comparison\\' . $className);
             // Skip interfaces and abstracts
             if (!$reflectClass->isInstantiable() || !$reflectClass->implementsInterface('\\Verdict\\Filter\\Comparison\\ComparisonInterface') || $className === 'Truth') {
                 continue;
             }
             $reflectMethod = $reflectClass->getMethod('getDisplay');
             $this->comparisonCache[lcfirst($className)] = $reflectMethod->invoke(null);
         }
         // First, lowercase our sort order array
         $sortOrder = array_map('lcfirst', $this->sortOrder);
         // Next, sort our keys based on their position inside our sort order array
         uksort($this->comparisonCache, function ($a, $b) use($sortOrder) {
             return array_search($a, $sortOrder) - array_search($b, $sortOrder);
         });
     }
     return $this->comparisonCache;
 }
 /**
  * {@inheritdoc}
  */
 public function getFunctions()
 {
     return ['getsearchresultsnippet' => new \Twig_SimpleFunction('getSearchResultSnippet', function ($object) {
         $pathArray = explode('\\', get_class($object));
         return 'SyliusSearchBundle:SearchResultSnippets:' . lcfirst(array_pop($pathArray)) . '.html.twig';
     })];
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 protected function extractAttributes($object, $format = null, array $context = array())
 {
     // If not using groups, detect manually
     $attributes = array();
     // methods
     $reflClass = new \ReflectionClass($object);
     foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
         if ($reflMethod->getNumberOfRequiredParameters() !== 0 || $reflMethod->isStatic() || $reflMethod->isConstructor() || $reflMethod->isDestructor()) {
             continue;
         }
         $name = $reflMethod->name;
         if (0 === strpos($name, 'get') || 0 === strpos($name, 'has')) {
             // getters and hassers
             $attributeName = lcfirst(substr($name, 3));
         } elseif (strpos($name, 'is') === 0) {
             // issers
             $attributeName = lcfirst(substr($name, 2));
         }
         if ($this->isAllowedAttribute($object, $attributeName)) {
             $attributes[$attributeName] = true;
         }
     }
     // properties
     foreach ($reflClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $reflProperty) {
         if ($reflProperty->isStatic() || !$this->isAllowedAttribute($object, $reflProperty->name)) {
             continue;
         }
         $attributes[$reflProperty->name] = true;
     }
     return array_keys($attributes);
 }
Example #11
0
 /**
  * Generates set of code based on data.
  *
  * @return array
  */
 public function generate()
 {
     $this->prepareData($this->data);
     $columnFields = ['name', 'description', 'label'];
     $table = $this->describe->getTable($this->data['name']);
     foreach ($table as $column) {
         if ($column->isAutoIncrement()) {
             continue;
         }
         $field = strtolower($column->getField());
         $method = 'set_' . $field;
         $this->data['camel'][$field] = lcfirst(camelize($method));
         $this->data['underscore'][$field] = underscore($method);
         array_push($this->data['columns'], $field);
         if ($column->isForeignKey()) {
             $referencedTable = Tools::stripTableSchema($column->getReferencedTable());
             $this->data['foreignKeys'][$field] = $referencedTable;
             array_push($this->data['models'], $referencedTable);
             $dropdown = ['list' => plural($referencedTable), 'table' => $referencedTable, 'field' => $field];
             if (!in_array($field, $columnFields)) {
                 $field = $this->describe->getPrimaryKey($referencedTable);
                 $dropdown['field'] = $field;
             }
             array_push($this->data['dropdowns'], $dropdown);
         }
     }
     return $this->data;
 }
 public function formatAction($action, $suffix)
 {
     if ($this->isDefaultAction($action)) {
         return is_null($suffix) ? RouterParameter::DEFAULT_ACTION_METHOD : RouterParameter::DEFAULT_ACTION_NAME_URL . $suffix;
     }
     return lcfirst(StringUtils::camelize($action)) . $suffix;
 }
Example #13
0
 /**
  * @param ExampleEvent $event
  */
 protected function printException(ExampleEvent $event)
 {
     if (null === ($exception = $event->getException())) {
         return;
     }
     $title = str_replace('\\', DIRECTORY_SEPARATOR, $event->getSpecification()->getTitle());
     $title = str_pad($title, 50, ' ', STR_PAD_RIGHT);
     $message = $this->getPresenter()->presentException($exception, $this->io->isVerbose());
     if ($exception instanceof PendingException) {
         $this->io->writeln(sprintf('<pending-bg>%s</pending-bg>', $title));
         $this->io->writeln(sprintf('<lineno>%4d</lineno>  <pending>- %s</pending>', $event->getExample()->getFunctionReflection()->getStartLine(), $event->getExample()->getTitle()));
         $this->io->writeln(sprintf('<pending>%s</pending>', lcfirst($message)), 6);
         $this->io->writeln();
     } elseif ($exception instanceof SkippingException) {
         if ($this->io->isVerbose()) {
             $this->io->writeln(sprintf('<skipped-bg>%s</skipped-bg>', $title));
             $this->io->writeln(sprintf('<lineno>%4d</lineno>  <skipped>? %s</skipped>', $event->getExample()->getFunctionReflection()->getStartLine(), $event->getExample()->getTitle()));
             $this->io->writeln(sprintf('<skipped>%s</skipped>', lcfirst($message)), 6);
             $this->io->writeln();
         }
     } elseif (ExampleEvent::FAILED === $event->getResult()) {
         $this->io->writeln(sprintf('<failed-bg>%s</failed-bg>', $title));
         $this->io->writeln(sprintf('<lineno>%4d</lineno>  <failed>✘ %s</failed>', $event->getExample()->getFunctionReflection()->getStartLine(), $event->getExample()->getTitle()));
         $this->io->writeln(sprintf('<failed>%s</failed>', lcfirst($message)), 6);
         $this->io->writeln();
     } else {
         $this->io->writeln(sprintf('<broken-bg>%s</broken-bg>', $title));
         $this->io->writeln(sprintf('<lineno>%4d</lineno>  <broken>! %s</broken>', $event->getExample()->getFunctionReflection()->getStartLine(), $event->getExample()->getTitle()));
         $this->io->writeln(sprintf('<broken>%s</broken>', lcfirst($message)), 6);
         $this->io->writeln();
     }
 }
Example #14
0
 public function __call($method, $args)
 {
     if (preg_match('/(set|get)([A-Z][a-zA-Z]*)/', $method, $matches) === 0) {
         throw new \BadMethodCallException("Invalid method name: {$method}");
     }
     $type = $matches[1];
     $attr = lcfirst($matches[2]);
     if (!in_array($attr, array_keys($this->nodes))) {
         $attr = preg_replace('/([A-Z][a-z]*)/', '-$1', $attr);
         $attr = strtolower($attr);
         if (!in_array($attr, array_keys($this->nodes))) {
             throw new \BadMethodCallException("Invalid attribute name: {$attr}");
         }
     }
     if ($type == 'get') {
         return $this->nodes[$attr];
     }
     if (!is_array($args) || count($args) == 0) {
         throw new \InvalidArgumentException("Missing method arguments: {$method}");
     }
     if (count($args) > 1) {
         throw new \InvalidArgumentException('Expected 1 argument. ' . count($args) . ' passed.');
     }
     $this->nodes[$attr] = reset($args);
     return $this;
 }
 public function beforeAction($action)
 {
     //log flush instantly
     \Yii::$app->getLog()->flushInterval = 1;
     foreach (\Yii::$app->getLog()->targets as $logTarget) {
         $logTarget->exportInterval = 1;
     }
     $module = $this->module;
     $this->realClient = new \GearmanWorker();
     if (!empty($module) && isset(\Yii::$app->params['gearman'][$module->getUniqueId()])) {
         $this->group = $module->getUniqueId();
     }
     $this->realClient->addServers(\Yii::$app->params['gearman'][$this->group]);
     /**
      * 注册可用的方法
      */
     $methods = get_class_methods(get_class($this));
     if ($methods) {
         $this->stdout("Available worker:" . PHP_EOL, Console::BOLD);
         foreach ($methods as $method) {
             if (substr($method, 0, strlen($this->callbackPrefix)) == $this->callbackPrefix) {
                 $funcName = "{$module->id}/{$this->id}/" . lcfirst(substr($method, strlen($this->callbackPrefix)));
                 $this->stdout("\t" . $funcName . PHP_EOL);
                 $that = $this;
                 $this->realClient->addFunction($funcName, function ($gearmanJob) use($that, $method) {
                     call_user_func([$that, $method], $gearmanJob);
                     $that->cleanUp();
                 });
             }
         }
     }
     return parent::beforeAction($action);
 }
Example #16
0
 public function __set($attribute, $value)
 {
     $attribute = lcfirst($attribute);
     if (isset($this->{$attribute})) {
         $this->{$attribute} = $value;
     }
 }
Example #17
0
 /**  
  * Constructor.
  * moduleName, controllerName, actionName is set in this method.
  * @param string $moduleName module name.
  * @param string $controllerName controller name.
  * @param string $actionName action name.
  */
 public function __construct($moduleName, $controllerName, $actionName)
 {
     /*{{{*/
     $this->moduleName = lcfirst($moduleName);
     $this->controllerName = lcfirst($controllerName);
     $this->actionName = lcfirst($actionName);
 }
 /**
  * One stop shop for an edit in place object property
  *
  * @param $opts array:
  *					'url' 		=> string - default backend genericController method
  *					'wysiwyg' 	=> BOOL - default false
  */
 public function ajaxFormField($fieldName, $opts = null)
 {
     $value = $this->obj->{$fieldName}();
     $id = lcfirst($this->obj->getClass()) . "_" . $fieldName . '_' . $this->obj->id();
     //---------------------------- $opts['url']
     $url = isset($opts['url']) ? $opts['url'] : '?adminAction=genericEditField&adminLayout=empty&ajax=true';
     //---------------------------- $opts['wysiwyg']
     if ($opts['wysiwyg']) {
         $this->accelJs()->wysiwyg();
     } else {
         $value = htmlentities($value);
     }
     $this->accelJs()->ready("\n            \$('.ajax-editable-link').unbind('click').click(function(){\n                var mySpanID = \$(this).attr('id').replace('_link', '');\n                var pieces = mySpanID.split('_');\n\t\t\t\tvar myInput = \$('.ajax-editable-input[name='+mySpanID+']');\n                var me = \$(this);\n                // we're saving\n                if(\$(this).hasClass('save')){\n\t                me.html('" . AccelJS::escape(FormBuilder::adminIcon('spinner')) . "');\n                    \$.ajax({\n                        type     : 'post',\n                        url        : '{$url}',\n                        data    : {\n                            className     : pieces[0],\n                            field        : pieces[1],\n                            id            : pieces[2],\n                            value        : myInput.val()\n                        },\n                        success    : function(ret){\n\t\t\t\t\t\t\tif(myInput.hasClass('mceEditor')){\n\t\t\t\t\t\t\t\tmyInput.ckeditorGet().destroy();\n\n\t\t\t\t\t\t\t\t\$('#' + mySpanID).html(ret);\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\$('#' + mySpanID).html(htmlentities(ret));\n\n\t\t\t\t\t\t\t}\n                            me.html('" . AccelJS::escape(FormBuilder::adminIcon('file_edit')) . "');\n                            me.removeClass('save');\n                        }\n\n                    });\n\n\n                // we're editing\n                } else {\n\t\t\t\t\tif(me.hasClass('wysiwyg')){\n\t\t\t\t\t\tvar editableInput = \$(document.createElement('textarea'))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr('name', mySpanID)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.val(\$('#' + mySpanID).html())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.addClass('ajax-editable-input')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.addClass('mceEditor');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar editableInput = \$(document.createElement('input'))\n\t\t\t\t\t\t\t\t\t\t\t\t.attr('name', mySpanID)\n\t\t\t\t\t\t\t\t\t\t\t\t.val(\$('#' + mySpanID).text())\n\t\t\t\t\t\t\t\t\t\t\t\t.addClass('ajax-editable-input');\n\t\t\t\t\t}\n\n\n                    \$('#' + mySpanID).html(editableInput);\n\n\t\t\t\t\tif(editableInput.hasClass('mceEditor')){\n\t\t\t\t\t\t" . $this->accelJs()->wysiwygJs($opts['wysiwyg']) . "\n\t\t\t\t\t}\n\n                    accelJS.ajaxEditableInputCheck();\n\n                    \$(this).html('" . AccelJS::escape(FormBuilder::adminIcon('save')) . "');\n                    \$(this).addClass('save');\n                }\n            });\n            accelJS.ajaxEditableInputCheck();\n\n\n        ");
     $this->accelJs()->js("\n            accelJS.ajaxEditableInputCheck =  function(){\n                \$('input.ajax-editable-input').unbind('keyup').keyup(function(e){\n                    if(e.keyCode == 13) {\n                        \$(this).parent().next('a').click();\n                    }\n                });\n            }\n        ");
     $addClass = $opts['wysiwyg'] ? 'wysiwyg' : '';
     $ret .= "<span class='ajax-editable' id='" . $id . "'>" . $value . "</span><a class='ajax-editable-link pointer {$addClass}' id='" . $id . "_link'>" . FormBuilder::adminIcon('file_edit') . "</a>";
     /*
             if($value){
                 $ret .= "<span class='ajax-editable' id='".$id."'>".htmlentities($value)."</span><a class='ajax-editable-link pointer' id='".$id."_link'>".FormBuilder::adminIcon('file_edit')."</a>";
             } else {
                 $ret .= "<span class='ajax-editable' id='".$id."'><input type='text' name='$id' class='ajax-editable-input'  /></span><a class='ajax-editable-link pointer save' id='".$id."_link'>".FormBuilder::adminIcon('save')."</a>";
             }
     */
     return $ret;
 }
Example #19
0
 protected function _createFunctionExportClass()
 {
     $function = $this->createFunction('exportClass');
     $function->setSignature(array('array &$class', '$overwrite = false'));
     $body = array('parent::exportClass($class, $overwrite);', '', 'if (array_key_exists(\'' . $this->_class['class_id'] . '\', $class[\'handlers\'])) {', '    foreach ($class[\'handlers\'][\'' . $this->_class['class_id'] . '\']', '             as $contentType => $' . lcfirst($this->_class['class_name_plural']) . ') {', '', '        $contentTypeName = str_replace(" ", "", ucwords(', '            str_replace("_", " ", $contentType)));', '', '        $class[\'content_type\'] = $contentType;', '        $phpFile = ThemeHouse_AddOnManager_PhpFile::create(', '            \'' . $this->_class['addon_id'] . '_PhpFile_' . $this->_class['class_name'] . '\',', '            $class[\'addon_id\'] . \'_' . $this->_class['class_name'] . '_\' . $contentTypeName,', '            $class', '        );', '', '        $phpFile->export($overwrite);', '    }', '}');
     $function->setBody($body);
 }
Example #20
0
 /**
  * @return string
  */
 public function resolve()
 {
     $bundle = $this->dashToCamelCase($this->request->attributes->get('module'));
     $controller = $this->dashToCamelCase($this->request->attributes->get('controller'));
     $action = lcfirst($this->dashToCamelCase($this->request->attributes->get('action')));
     return $bundle . '/' . $controller . '/' . $action;
 }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $annotClass = 'Symfony\\Component\\Validator\\Constraints\\Validation';
     $reflClass = $metadata->getReflectionClass();
     $loaded = false;
     if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) {
         foreach ($annot->constraints as $constraint) {
             $metadata->addConstraint($constraint);
         }
         $loaded = true;
     }
     foreach ($reflClass->getProperties() as $property) {
         if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) {
             foreach ($annot->constraints as $constraint) {
                 $metadata->addPropertyConstraint($property->getName(), $constraint);
             }
             $loaded = true;
         }
     }
     foreach ($reflClass->getMethods() as $method) {
         if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) {
             foreach ($annot->constraints as $constraint) {
                 // TODO: clean this up
                 $name = lcfirst(substr($method->getName(), 0, 3) == 'get' ? substr($method->getName(), 3) : substr($method->getName(), 2));
                 $metadata->addGetterConstraint($name, $constraint);
             }
             $loaded = true;
         }
     }
     return $loaded;
 }
Example #22
0
 /**
  * 获取自动加载中的文件定位(基本路径)
  * @access private
  * @param  mixed $class
  * @author songdengtao <http://www.songdengtao.cn>
  * @return string
  */
 private static function _GetClassFileBasePath(&$class)
 {
     $root = static::$_pandaphp->get('root');
     $appPath = static::$_pandaphp->get('appPath');
     $frameworkPath = static::$_pandaphp->get('frameworkPath');
     $venderPath = static::$_pandaphp->get('venderPath');
     $name = strstr($class, '\\', true);
     if ($name) {
         if (lcfirst($name) === 'pandaphp') {
             $class = str_replace('pandaphp\\', '', $class);
             $basepath = $frameworkPath;
         } elseif (is_dir($root . $name)) {
             $basepath = $root;
         } else {
             $basepath = $appPath;
         }
     } else {
         $temp = lcfirst($class);
         if (is_dir($frameworkPath . 'sysvender/' . $temp)) {
             $basepath = $frameworkPath . 'sysvender/' . $temp . '/';
         } else {
             $basepath = $venderPath;
         }
     }
     return $basepath;
 }
Example #23
0
 /**
  * Returns PHP code that, when executed in $from, will return the path to $to
  *
  * @param string $from
  * @param string $to
  * @param Boolean $directories if true, the source/target are considered to be directories
  * @return string
  */
 public function findShortestPathCode($from, $to, $directories = false)
 {
     if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
         throw new \InvalidArgumentException('from and to must be absolute paths');
     }
     if ($from === $to) {
         return $directories ? '__DIR__' : '__FILE__';
     }
     $from = lcfirst(strtr($from, '\\', '/'));
     $to = lcfirst(strtr($to, '\\', '/'));
     $commonPath = $to;
     while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
         $commonPath = strtr(dirname($commonPath), '\\', '/');
     }
     if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
         return var_export($to, true);
     }
     $commonPath = rtrim($commonPath, '/') . '/';
     if (strpos($to, $from . '/') === 0) {
         return '__DIR__ . ' . var_export(substr($to, strlen($from)), true);
     }
     $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
     $commonPathCode = str_repeat('dirname(', $sourcePathDepth) . '__DIR__' . str_repeat(')', $sourcePathDepth);
     $relTarget = substr($to, strlen($commonPath));
     return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
 }
 /**
  * {@inheritDoc}
  */
 public function load(array $configs, ContainerBuilder $container)
 {
     $configuration = new Configuration();
     $config = $this->processConfiguration($configuration, $configs);
     $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
     $loader->load('services.yml');
     foreach ($config['actions'] as $key => $value) {
         if ($value['max_number_by_ip']) {
             $definition = new Definition('Kunstmaan\\VotingBundle\\EventListener\\Security\\MaxNumberByIpEventListener');
             $definition->addArgument(new Reference('kunstmaan_voting.services.repository_resolver'));
             $definition->addArgument($value['max_number_by_ip']);
             $definition->addTag('kernel.event_listener', array('event' => 'kunstmaan_voting.' . lcfirst(ContainerBuilder::camelize($key)), 'method' => 'onVote', 'priority' => 100));
             $container->setDefinition('kunstmaan_voting.security.' . $key . '.max_number_by_ip_event_listener', $definition);
         }
     }
     $possibleActions = array('up_vote', 'down_vote', 'facebook_like', 'facebook_send', 'linkedin_share');
     $votingDefaultValue = $config['voting_default_value'];
     // If the user overwrites the voting_default_value in paramters file, we use this one
     if ($container->hasParameter('voting_default_value')) {
         $votingDefaultValue = $container->getParameter('voting_default_value');
     }
     // When no values are defined, initialize with defaults
     foreach ($possibleActions as $action) {
         if (!isset($config['actions'][$action]) || !is_array($config['actions'][$action])) {
             $config['actions'][$action]['default_value'] = $action == 'down_vote' ? -1 * $votingDefaultValue : $votingDefaultValue;
         }
     }
     $container->setParameter('kuma_voting.actions', $config['actions']);
 }
Example #25
0
 /**
  * method to invoke direct method-call of View-Part on "to-string" event
  * @throws \Exception
  * @return string
  */
 public function __toString()
 {
     if (empty($this->_direct) || !method_exists($this, lcfirst($this->_direct))) {
         throw new \Exception('Method ' . lcfirst($this->_direct) . ' was not found in ' . get_class($this));
     }
     return $this->{lcfirst($this->_direct)}();
 }
Example #26
0
 public function getModuleActions($module_class, $use_admin_prefix = false)
 {
     $actions = array();
     $controllers_dir = MODULES_PATH . lcfirst(str_replace('Module', '', $module_class)) . '/controllers/';
     $controllers = scandir($controllers_dir);
     foreach ($controllers as $controller) {
         if ($controller[0] == ".") {
             continue;
         }
         $class = str_replace('.php', '', $controller);
         if (!class_exists($class, false)) {
             require_once $controllers_dir . $controller;
         }
         $reflection = new ReflectionClass($class);
         if (!in_array($reflection->getParentClass()->name, array('BaseController', 'AdminController'))) {
             continue;
         }
         $actions_titles = call_user_func(array($class, 'actionsTitles'));
         $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
         foreach ($methods as $method) {
             if (in_array($method->name, array('actionsTitles', 'actions')) || mb_substr($method->name, 0, 6, 'utf-8') != 'action') {
                 continue;
             }
             $action = str_replace('action', '', $method->name);
             $action_name = str_replace('Controller', '', $class) . '_' . $action;
             $title = isset($actions_titles[$action]) ? $actions_titles[$action] : "";
             if ($title && $use_admin_prefix && strpos($action_name, "Admin_") !== false) {
                 $title .= " (админка)";
             }
             $actions[$action_name] = $title;
         }
     }
     return $actions;
 }
Example #27
0
 /**
  * Convert a value to camel case.
  *
  * @param string $value
  *
  * @return string
  */
 public static function camel($value)
 {
     if (isset(static::$camelCache[$value])) {
         return static::$camelCache[$value];
     }
     return static::$camelCache[$value] = lcfirst(static::studly($value));
 }
 /**
  * Prune any fields not valid for Marketo insertion.
  *
  * @param $fields
  *   Array of fields to prune, indexed by field name.
  * @return
  *   Pruned array of fields.
  */
 public function pruneFields($fields)
 {
     $valid = [];
     foreach ($fields as $key => $field) {
         if (in_array($key, config('marketo.fields.valid'))) {
             // Check for ignored fields.
             if (in_array($key, config('marketo.fields.ignore')) && empty($field)) {
                 // Don't pass.
                 continue;
             }
             // Serialize answers as comma-separated values for storage.
             if (is_array($field)) {
                 $values = [];
                 foreach ($field as $option) {
                     // Don't include unchecked options.
                     if (!empty($option)) {
                         $values[] = $option;
                     }
                 }
                 $field = implode(',', $values);
             }
             // Ensure that key matches REST (vs. SOAP) format.
             $valid[lcfirst($key)] = $field;
         }
     }
     return $valid;
 }
Example #29
0
 /**
  * {@inheritdoc}
  */
 public function getProperties($class, array $context = array())
 {
     try {
         $reflectionClass = new \ReflectionClass($class);
     } catch (\ReflectionException $reflectionException) {
         return;
     }
     $reflectionProperties = $reflectionClass->getProperties();
     $properties = array();
     foreach ($reflectionProperties as $reflectionProperty) {
         if ($reflectionProperty->isPublic()) {
             $properties[$reflectionProperty->name] = true;
         }
     }
     foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
         $propertyName = $this->getPropertyName($reflectionMethod->name, $reflectionProperties);
         if (!$propertyName || isset($properties[$propertyName])) {
             continue;
         }
         if (!preg_match('/^[A-Z]{2,}/', $propertyName)) {
             $propertyName = lcfirst($propertyName);
         }
         $properties[$propertyName] = true;
     }
     return array_keys($properties);
 }
 private function writeCountryCallingCodeMappingToFile($countryCodeToRegionCodeMap, $outputDir, $mappingClass)
 {
     // Find out whether the countryCodeToRegionCodeMap has any region codes or country
     // calling codes listed in it.
     $hasRegionCodes = false;
     foreach ($countryCodeToRegionCodeMap as $key => $listWithRegionCode) {
         if (count($listWithRegionCode) > 0) {
             $hasRegionCodes = true;
             break;
         }
     }
     $hasCountryCodes = count($countryCodeToRegionCodeMap) > 1;
     $variableName = lcfirst($mappingClass);
     $data = '<?php' . PHP_EOL . self::GENERATION_COMMENT . PHP_EOL . "namespace libphonenumber;" . PHP_EOL . "class {$mappingClass} {" . PHP_EOL . PHP_EOL;
     if ($hasRegionCodes && $hasCountryCodes) {
         $data .= self::MAP_COMMENT . PHP_EOL;
         $data .= "   public static \${$variableName} = " . var_export($countryCodeToRegionCodeMap, true) . ";" . PHP_EOL;
     } elseif ($hasCountryCodes) {
         $data .= self::COUNTRY_CODE_SET_COMMENT . PHP_EOL;
         $data .= "   public static \${$variableName} = " . var_export(array_keys($countryCodeToRegionCodeMap), true) . ";" . PHP_EOL;
     } else {
         $data .= self::REGION_CODE_SET_COMMENT . PHP_EOL;
         $data .= "   public static \${$variableName} = " . var_export($countryCodeToRegionCodeMap[0], true) . ";" . PHP_EOL;
     }
     $data .= PHP_EOL . "}" . PHP_EOL . '/* EOF */';
     file_put_contents($outputDir . $mappingClass . '.php', $data);
 }