public function getChangeDescription()
 {
     if ($this->count === 1) {
         return $this->changeInfos[0]->getChangeDescription();
     }
     return Strings::firstUpper(StringUtils::verbToPastTense($this->getAction())) . " {$this->count} term-meta";
 }
 /**
  * @param Task $task
  * @param \SimpleXMLElement|null $pmml
  * @param DatabaseFactory $databaseFactory
  * @param PreprocessingFactory $preprocessingFactory
  * @param string $appVersion =''
  */
 public function __construct(Task $task, \SimpleXMLElement $pmml = null, DatabaseFactory $databaseFactory, PreprocessingFactory $preprocessingFactory, $appVersion = '')
 {
     if ($task instanceof Task) {
         $this->task = $task;
         $this->miner = $task->miner;
     }
     $this->appVersion = $appVersion;
     if (!empty($pmml)) {
         if ($pmml instanceof \SimpleXMLElement) {
             $this->pmml = $pmml;
         } elseif (is_string($pmml)) {
             $this->pmml = simplexml_load_string($pmml);
         }
     }
     if (!$pmml instanceof \SimpleXMLElement) {
         $this->prepareBlankPmml();
     }
     $this->appendTaskInfo();
     $this->databaseFactory = $databaseFactory;
     $this->preprocessingFactory = $preprocessingFactory;
     $connectivesArr = Cedent::getConnectives();
     foreach ($connectivesArr as $connective) {
         $this->connectivesArr[$connective] = Strings::firstUpper($connective);
     }
 }
 /**
  * @param string $name
  * @return string
  */
 public function annotationBeautify($name)
 {
     if (isset($this->rename[$name])) {
         $name = $this->rename[$name];
     }
     return Nette\Utils\Strings::firstUpper($name);
 }
Example #4
0
 /**
  * Check value of dimension
  *
  * @param int|string $dimension
  * @param string $type
  */
 private function checkDimension($dimension, $type)
 {
     // dimension must be number or percent
     if (Validators::is($dimension, 'string') && !Validators::isNumeric($dimension) && !Strings::endsWith($dimension, '%')) {
         $msg = sprintf('Dimension of %s has unexpected format, "%s" given.', $type, $dimension);
         throw new InvalidArgumentException($msg);
     }
     // dimension cannot be negative number
     if ((int) $dimension < 0) {
         $msg = sprintf('Dimension of %s must be greater than 0, "%s" given.', $type, $dimension);
         throw new InvalidArgumentException($msg);
     }
     // cannot be generate new image greater than 200 % of original image
     // is number
     $originDimension = $this->image->{'get' . Strings::firstUpper($type)}();
     if (Validators::isNumeric($dimension) && $dimension > $originDimension * 2) {
         $msg = sprintf('Required %s cannot be greater than 200 percent of original, "%s" required and "%s" is original.', $type, $dimension, $originDimension);
         throw new InvalidArgumentException($msg);
     }
     // is percent
     if (Strings::endsWith($dimension, '%') && (int) $dimension > 200) {
         $msg = sprintf('Required %s cannot be greater than 200 percent of original, "%s" required.', $type, $dimension);
         throw new InvalidArgumentException($msg);
     }
 }
 public function getChangeDescription()
 {
     $verb = "Edited";
     $subject = "term-meta '{$this->metaKey}'";
     $rest = "for term '{$this->termName}'";
     if ($this->getAction() === "create" || $this->getAction() === "delete") {
         $verb = Strings::firstUpper(StringUtils::verbToPastTense($this->getAction()));
     }
     return sprintf("%s %s %s", $verb, $subject, $rest);
 }
Example #6
0
 private function loadCategories()
 {
     try {
         $categories = $this->categoryFacade->findAll();
         foreach ($categories->items as $category) {
             $this->categories[$category->id] = Strings::firstUpper($category->name);
         }
     } catch (EntitiesNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
     }
 }
 /**
  * @param string
  */
 public function signalReceived($signal)
 {
     $methodName = sprintf('handle%s', \Nette\Utils\Strings::firstUpper($signal));
     if (!method_exists($this, $methodName)) {
         throw new \Nette\Application\UI\BadSignalException(sprintf('Method %s does not exist', $methodName));
     }
     $presenterComponentReflection = new PresenterComponentReflection(get_called_class());
     $methodReflection = $presenterComponentReflection->getMethod($methodName);
     $args = $presenterComponentReflection->combineArgs($methodReflection, $this->params);
     $methodReflection->invokeArgs($this, $args);
 }
 /**
  * @param \App\type $id
  * @return \App\PresenterLinkSettings
  */
 public function create($id)
 {
     $item = $this->menuItemDataSource->get($id, function (Selection $context) {
         $pageKey = ':menu_has_presenter.presenter.code';
         $context->select('section.module, menu.section_id, menu.name');
         $context->select("{$pageKey}");
         $context->where("{$pageKey} IS NOT NULL");
     });
     $module = Strings::capitalize($item->module);
     $presenter = Strings::firstUpper($item->code);
     return $this->presenterLinkSettingsFactory->create(":{$module}:{$presenter}:", []);
 }
Example #9
0
 public function getChangeDescription()
 {
     $taxonomy = $this->getTaxonomyName();
     switch ($this->getAction()) {
         case "create":
             return "New {$taxonomy} '{$this->termName}'";
         case "delete":
             return "Deleted {$taxonomy} '{$this->termName}'";
         case "rename":
             return Strings::firstUpper($taxonomy) . " '{$this->oldTermName}' renamed to '{$this->termName}'";
     }
     return "Edited {$taxonomy} '{$this->termName}'";
 }
Example #10
0
 /**
  * Constructor
  */
 public function __construct()
 {
     // get wordpress database object (no injection sorry!
     global $wpdb;
     // variables
     $this->database = $wpdb;
     $this->settings = new \SimpleSubscribe\Settings(SUBSCRIBE_KEY);
     $this->settingsAll = $this->settings->getSettings();
     // we get the table name from class name
     preg_match('#Repository(\\w+)$#', get_class($this), $class);
     $tablePreName = \Nette\Utils\Strings::contains($class[1], 'Subscribers') ? $class[1] : 'Subscribers' . $class[1];
     $this->tableName = $this->database->prefix . Utils::camelCaseToUnderscore($tablePreName);
     $this->tableSingleName = \Nette\Utils\Strings::firstUpper($class[1]);
     $this->count = $this->count();
 }
Example #11
0
 /**
  * Maps HTTP request to a Request object.
  * @param \Nette\Http\IRequest $httpRequest
  * @return \Nette\Application\Request|NULL
  */
 public function match(IRequest $httpRequest)
 {
     $url = $httpRequest->getUrl();
     $basePath = Strings::replace($url->getBasePath(), '/\\//', '\\/');
     $cleanPath = Strings::replace($url->getPath(), "/^{$basePath}/");
     $path = Strings::replace($this->getPath(), '/\\//', '\\/');
     $pathRexExp = empty($path) ? "/^.+\$/" : "/^{$path}\\/.*\$/";
     if (!Strings::match($cleanPath, $pathRexExp)) {
         return NULL;
     }
     $cleanPath = Strings::replace($cleanPath, '/^' . $path . '\\//');
     $params = array();
     $path = $cleanPath;
     $params['action'] = $this->detectAction($httpRequest);
     $frags = explode('/', $path);
     // Resource ID.
     if (count($frags) % 2 === 0) {
         $params['id'] = array_pop($frags);
     } elseif ($params['action'] == 'read' && $this->useReadAllAction) {
         $params['action'] = 'readAll';
     }
     $presenterName = Strings::firstUpper(array_pop($frags));
     // Allow to use URLs like domain.tld/presenter.format.
     $formats = join('|', array_keys($this->formats));
     if (Strings::match($presenterName, "/.+\\.({$formats})\$/")) {
         list($presenterName, $format) = explode('.', $presenterName);
     }
     // Associations.
     $assoc = array();
     if (count($frags) > 0 && count($frags) % 2 === 0) {
         foreach ($frags as $k => $f) {
             if ($k % 2 !== 0) {
                 continue;
             }
             $assoc[$f] = $frags[$k + 1];
         }
     }
     $params['format'] = $this->detectFormat($httpRequest);
     $params['associations'] = $assoc;
     $params['data'] = $this->readInput();
     $params['query'] = $httpRequest->getQuery();
     $presenterName = empty($this->module) ? $presenterName : $this->module . ':' . $presenterName;
     $appRequest = new Request($presenterName, $httpRequest->getMethod(), $params);
     return $appRequest;
 }
 protected function createComponentSearchForm()
 {
     $form = new \Nette\Forms\BootstrapPHForm();
     $form->setTranslator($this->presenter->translator->domain('dictionary.main'));
     $form->setMethod("GET");
     $form->getElementPrototype()->class = "form-inline";
     $form->getElementPrototype()->role = 'form';
     $form->getElementPrototype()->autocomplete = 'off';
     $form->addHidden('idr', 'ID:');
     $form->addText('src')->setAttribute("class", "form-control")->setAttribute("placeholder", \Nette\Utils\Strings::firstUpper("src"));
     $form->addText("priceFrom")->setAttribute("style", "width: 50px;");
     $form->addText("priceTo")->setAttribute("style", "width: 50px;");
     $form->addText("brand");
     if ($this->getParameter("id")) {
         $form->setDefaults(array("idr" => $this->presenter->getParameter("id")));
     }
     $form->addSubmit('submitm', 'dictionary.main.Search')->setAttribute("class", "btn btn-info btn-lg");
     $form->onSuccess[] = $this->searchFormSucceeded;
     return $form;
 }
 public function getChangeDescription()
 {
     $verb = "Edited";
     $subject = "post-meta '{$this->metaKey}'";
     $rest = "for {$this->postType} '{$this->postTitle}'";
     if ($this->metaKey === "_thumbnail_id") {
         // featured image
         $verb = "Changed";
         $subject = "featured image";
         if ($this->getAction() === "create") {
             $verb = "Set";
         }
         if ($this->getAction() === "delete") {
             $verb = "Removed";
         }
     } elseif ($this->getAction() === "create" || $this->getAction() === "delete") {
         $verb = Strings::firstUpper(StringUtils::verbToPastTense($this->getAction()));
     }
     return sprintf("%s %s %s", $verb, $subject, $rest);
 }
Example #14
0
 public function match(IRequest $httpRequest)
 {
     $url = $httpRequest->getUrl();
     $basePath = Strings::replace($url->getBasePath(), '/\\//', '\\/');
     $cleanPath = Strings::replace($url->getPath(), "/^" . $basePath . "/");
     $path = Strings::replace($this->_getPath(), '/\\//', '\\/');
     $pathRexExp = empty($path) ? "/^.+\$/" : "/^" . $path . "\\/.*\$/";
     if (!Strings::match($cleanPath, $pathRexExp)) {
         return;
     }
     $params = $httpRequest->getQuery();
     // Get presenter action
     if (!isset($params['action']) || empty($params['action'])) {
         $params['action'] = $this->_detectAction($httpRequest);
     }
     $frags = explode('/', Strings::replace($cleanPath, '/^' . $path . '\\//'));
     $resource = Strings::firstUpper($frags[0]);
     // Set 'id' parameter if not custom action
     if (isset($frags[1]) && $this->_isApiAction($params['action'])) {
         $params['id'] = $frags[1];
     }
     return new Request(empty($this->module) ? $resource : $this->module . ':' . $resource, $httpRequest->getMethod(), $params);
 }
Example #15
0
 /**
  * Render method hook
  *
  * @param string $func
  * @param array $args
  * @return mixed|void
  */
 public function __call($func, $args = [])
 {
     if (Nette\Utils\Strings::startsWith($func, 'render')) {
         // Fix array-in-array when passing parameters from template
         // See http://forum.nette.org/cs/21090-makro-control-obaluje-pojmenovane-parametry-polem (in czech)
         $tmp = @array_reduce($args, 'array_merge', []);
         // @ - intentionally
         if ($tmp === NULL) {
             $tmp = $args;
         }
         // Capitalize and validate view syntax
         $this->view = Nette\Utils\Strings::firstUpper($this->view);
         $this->checkView();
         // Call view and render methods
         $render = Nette\Utils\Strings::substring($func, 6);
         $this->callViewRender($render, $tmp);
         // Life cycle
         if ($this instanceof IHasControlLifeCycle) {
             return $this->run($render, $tmp);
         }
     }
     return parent::__call($func, $args);
 }
Example #16
0
 /**
  * Translates the given string.
  *
  * @param  string   message
  * @param  int      plural count
  * @return string
  */
 public function translate($message, $count = NULL, array $parameters = array())
 {
     $pluralization = $count !== NULL ? PluralizationRules::get($count, $this->lang) : 0;
     $lcMessage = lcfirst($message);
     $uc = ctype_upper(substr($message, 0, 1));
     $this->loadData();
     if (isset($this->data[$lcMessage])) {
         $ret = isset($this->data[$lcMessage][$pluralization]) ? $this->data[$lcMessage][$pluralization] : $this->data[$lcMessage][0];
     } else {
         $ret = explode('|', $message);
         $ret = isset($ret[$pluralization]) ? $ret[$pluralization] : $ret[0];
     }
     if ($count !== NULL) {
         $parameters += array('count' => $count);
     }
     foreach ($parameters as $key => $val) {
         $ret = str_replace('%' . $key . '%', $val, $ret);
     }
     if ($uc) {
         $ret = Strings::firstUpper($ret);
     }
     return $ret;
 }
 /**
  * Funkce pro serializaci TransformationDictionary
  * @param bool $includeFrequencies = true
  * @throws \Exception
  */
 public function appendTransformationDictionary($includeFrequencies = true)
 {
     $metasource = $this->miner->metasource;
     if (!$this->preprocessingFactory instanceof PreprocessingFactory) {
         throw new \Exception('Preprocessing factory is not configured properly.');
     }
     /** @var IPreprocessing $preprocessingDriver */
     $preprocessingDriver = $this->preprocessingFactory->getPreprocessingInstance($this->miner->metasource->getPpConnection(), $this->miner->user);
     if (empty($metasource->attributes)) {
         return;
     }
     /** @var \SimpleXMLElement $transformationDictionaryXml */
     $transformationDictionaryXml = $this->pmml->TransformationDictionary;
     foreach ($metasource->attributes as $attribute) {
         if (empty($attribute->preprocessing)) {
             continue;
         }
         $derivedFieldXml = $transformationDictionaryXml->addChild('DerivedField');
         $derivedFieldXml->addAttribute('name', $attribute->name);
         $derivedFieldXml->addAttribute('dataType', $this->dataTypesTransformationArr[$attribute->type]);
         if ($attribute->type == Attribute::TYPE_STRING) {
             $derivedFieldXml->addAttribute('optype', 'categorical');
         } else {
             $derivedFieldXml->addAttribute('optype', 'continuous');
         }
         $datasourceColumn = $attribute->datasourceColumn;
         //serializace preprocessingu
         $preprocessing = $attribute->preprocessing;
         if ($preprocessing->specialType == Preprocessing::SPECIALTYPE_EACHONE) {
             //serializace eachOne
             $mapValuesXml = $derivedFieldXml->addChild('MapValues');
             $mapValuesXml->addAttribute('outputColumn', 'field');
             $fieldColumnPairXml = $mapValuesXml->addChild('FieldColumnPair');
             $fieldColumnPairXml->addAttribute('column', 'column');
             $fieldColumnPairXml->addAttribute('field', $datasourceColumn->name);
             $inlineTableXml = $mapValuesXml->addChild('InlineTable');
             //frekvence
             $ppDataset = $preprocessingDriver->getPpDataset($metasource->ppDatasetId);
             $ppValues = $preprocessingDriver->getPpValues($ppDataset, $attribute->ppDatasetAttributeId ? $attribute->ppDatasetAttributeId : $attribute->name, 0, 100);
             //TODO optimalizovat počet hodnot
             if (!empty($ppValues)) {
                 if ($includeFrequencies) {
                     foreach ($ppValues as $ppValue) {
                         $this->addExtensionElement($inlineTableXml, 'Frequency', $ppValue->frequency, $ppValue->value, false);
                     }
                 }
                 foreach ($ppValues as $ppValue) {
                     if ($ppValue->value == '') {
                         continue;
                         //ignorujeme prázdné hodnoty
                     }
                     $rowXml = $inlineTableXml->addChild('row');
                     $columnNode = $rowXml->addChild('column');
                     //v původních i finálních datech je stejná hodnota
                     $columnNode[0] = $ppValue->value;
                     $fieldNode = $rowXml->addChild('field');
                     $fieldNode[0] = $ppValue->value;
                 }
             }
             continue;
         }
         if (empty($preprocessing->valuesBins)) {
             continue;
         }
         $valuesBins = $preprocessing->valuesBins;
         if (!empty($valuesBins[0]->intervals)) {
             //serializace discretizace pomocí intervalů
             $discretizeXml = $derivedFieldXml->addChild('Discretize');
             $discretizeXml->addAttribute('field', $datasourceColumn->name);
             //frekvence
             //TODO replace databasesFacade
             $valuesStatistics = $this->databasesFacade->getColumnValuesStatistic($metasource->attributesTable, $attribute->name);
             if (!empty($valuesStatistics->valuesArr) && $includeFrequencies) {
                 foreach ($valuesStatistics->valuesArr as $value => $count) {
                     $this->addExtensionElement($discretizeXml, 'Frequency', $count, $value);
                 }
             }
             foreach ($valuesBins as $valuesBin) {
                 if (!empty($valuesBin->intervals)) {
                     foreach ($valuesBin->intervals as $interval) {
                         if (!isset($valuesStatistics->valuesArr[$valuesBin->name])) {
                             continue;
                         }
                         //vynecháme neobsazené hodnoty
                         $discretizeBinXml = $discretizeXml->addChild('DiscretizeBin');
                         $discretizeBinXml->addAttribute('binValue', $valuesBin->name);
                         $intervalXml = $discretizeBinXml->addChild('Interval');
                         $closure = $interval->leftClosure . Strings::firstUpper($interval->rightClosure);
                         $intervalXml->addAttribute('closure', $closure);
                         $intervalXml->addAttribute('leftMargin', $interval->leftMargin);
                         $intervalXml->addAttribute('rightMargin', $interval->rightMargin);
                     }
                 }
             }
         } elseif (!empty($valuesBins[0]->values)) {
             //serializace discretizace pomocí výčtů hodnot
             $mapValuesXml = $derivedFieldXml->addChild('MapValues');
             $mapValuesXml->addAttribute('outputColumn', 'field');
             $fieldColumnPairXml = $mapValuesXml->addChild('FieldColumnPair');
             $fieldColumnPairXml->addAttribute('column', 'column');
             $fieldColumnPairXml->addAttribute('field', $datasourceColumn->name);
             $inlineTableXml = $mapValuesXml->addChild('InlineTable');
             //frekvence
             //TODO replace databasesFacade
             $valuesStatistics = $this->databasesFacade->getColumnValuesStatistic($metasource->attributesTable, $attribute->name);
             if (!empty($valuesStatistics->valuesArr) && $includeFrequencies) {
                 foreach ($valuesStatistics->valuesArr as $value => $count) {
                     $this->addExtensionElement($inlineTableXml, 'Frequency', $count, $value);
                 }
             }
             foreach ($valuesBins as $valuesBin) {
                 if (!empty($valuesBin->values)) {
                     if (!isset($valuesStatistics->valuesArr[$valuesBin->name])) {
                         continue;
                     }
                     //vynecháme neobsazené hodnoty
                     foreach ($valuesBin->values as $value) {
                         $rowXml = $inlineTableXml->addChild('row');
                         $columnNode = $rowXml->addChild('column');
                         $columnNode[0] = $value->value;
                         $fieldNode = $rowXml->addChild('field');
                         $fieldNode[0] = $valuesBin->name;
                     }
                 }
             }
         }
     }
 }
Example #18
0
 private function getMessageSuccess()
 {
     return $this->messageSuccess ?: ($this->name === NULL ? 'Akce byla úspěšně provedena.' : Strings::firstUpper($this->name) . ' proběhlo úspěšně.');
 }
 /**
  * Creates template.
  *
  * @param \ApiGen\Generator $generator
  */
 public function __construct(Generator $generator)
 {
     $this->generator = $generator;
     $this->config = $generator->getConfig();
     $that = $this;
     // Output in HTML5
     Nette\Utils\Html::$xhtml = false;
     // FSHL
     $fshl = new FSHL\Highlighter(new FSHL\Output\Html());
     $fshl->setLexer(new FSHL\Lexer\Php());
     // Texy
     $this->texy = new \Texy();
     $this->texy->allowedTags = array_flip($this->config->allowedHtml);
     $this->texy->allowed['list/definition'] = false;
     $this->texy->allowed['phrase/em-alt'] = false;
     $this->texy->allowed['longwords'] = false;
     $this->texy->allowed['typography'] = false;
     $this->texy->linkModule->shorten = false;
     // Highlighting <code>, <pre>
     $this->texy->addHandler('beforeParse', function ($texy, &$text, $singleLine) {
         $text = preg_replace('~<code>(.+?)</code>~', '#code#\\1#/code#', $text);
     });
     $this->texy->registerLinePattern(function ($parser, $matches, $name) use($fshl) {
         return \TexyHtml::el('code', $fshl->highlight($matches[1]));
     }, '~#code#(.+?)#/code#~', 'codeInlineSyntax');
     $this->texy->registerBlockPattern(function ($parser, $matches, $name) use($fshl) {
         if ('code' === $matches[1]) {
             $lines = array_filter(explode("\n", $matches[2]));
             if (!empty($lines)) {
                 $firstLine = array_shift($lines);
                 $indent = '';
                 $li = 0;
                 while (isset($firstLine[$li]) && preg_match('~\\s~', $firstLine[$li])) {
                     foreach ($lines as $line) {
                         if (!isset($line[$li]) || $firstLine[$li] !== $line[$li]) {
                             break 2;
                         }
                     }
                     $indent .= $firstLine[$li++];
                 }
                 if (!empty($indent)) {
                     $matches[2] = str_replace("\n" . $indent, "\n", 0 === strpos($matches[2], $indent) ? substr($matches[2], $li) : $matches[2]);
                 }
             }
             $content = $fshl->highlight($matches[2]);
         } else {
             $content = htmlspecialchars($matches[2]);
         }
         $content = $parser->getTexy()->protect($content, \Texy::CONTENT_BLOCK);
         return \TexyHtml::el('pre', $content);
     }, '~<(code|pre)>(.+?)</\\1>~s', 'codeBlockSyntax');
     // Common operations
     $this->registerHelperLoader('Nette\\Templating\\Helpers::loader');
     // PHP source highlight
     $this->registerHelper('highlightPHP', function ($source, $context) use($that, $fshl) {
         return $that->resolveLink($that->getTypeName($source), $context) ?: $fshl->highlight((string) $source);
     });
     $this->registerHelper('highlightValue', function ($definition, $context) use($that) {
         return $that->highlightPHP(preg_replace('~^(?:[ ]{4}|\\t)~m', '', $definition), $context);
     });
     // Urls
     $this->registerHelper('packageUrl', new Nette\Callback($this, 'getPackageUrl'));
     $this->registerHelper('namespaceUrl', new Nette\Callback($this, 'getNamespaceUrl'));
     $this->registerHelper('groupUrl', new Nette\Callback($this, 'getGroupUrl'));
     $this->registerHelper('classUrl', new Nette\Callback($this, 'getClassUrl'));
     $this->registerHelper('methodUrl', new Nette\Callback($this, 'getMethodUrl'));
     $this->registerHelper('propertyUrl', new Nette\Callback($this, 'getPropertyUrl'));
     $this->registerHelper('constantUrl', new Nette\Callback($this, 'getConstantUrl'));
     $this->registerHelper('functionUrl', new Nette\Callback($this, 'getFunctionUrl'));
     $this->registerHelper('elementUrl', new Nette\Callback($this, 'getElementUrl'));
     $this->registerHelper('sourceUrl', new Nette\Callback($this, 'getSourceUrl'));
     $this->registerHelper('manualUrl', new Nette\Callback($this, 'getManualUrl'));
     // Packages & namespaces
     $this->registerHelper('packageLinks', new Nette\Callback($this, 'getPackageLinks'));
     $this->registerHelper('namespaceLinks', new Nette\Callback($this, 'getNamespaceLinks'));
     $this->registerHelper('subgroupName', function ($groupName) {
         if ($pos = strrpos($groupName, '\\')) {
             return substr($groupName, $pos + 1);
         }
         return $groupName;
     });
     // Types
     $this->registerHelper('typeLinks', new Nette\Callback($this, 'getTypeLinks'));
     // Docblock descriptions
     $this->registerHelper('description', function ($annotation, $context) use($that) {
         $description = trim(strpbrk($annotation, "\n\r\t \$"));
         if ($context instanceof ReflectionParameter) {
             $description = preg_replace('~^(\\$' . $context->getName() . '(?:,\\.{3})?)(\\s+|$)~i', '\\2', $description, 1);
             $context = $context->getDeclaringFunction();
         }
         return $that->doc($description, $context);
     });
     $this->registerHelper('shortDescription', function ($element, $block = false) use($that) {
         return $that->doc($element->getShortDescription(), $element, $block);
     });
     $this->registerHelper('longDescription', function ($element) use($that) {
         $long = $element->getLongDescription();
         // Merge lines
         $long = preg_replace_callback('~(?:<(code|pre)>.+?</\\1>)|([^<]*)~s', function ($matches) {
             return !empty($matches[2]) ? preg_replace('~\\n(?:\\t|[ ])+~', ' ', $matches[2]) : $matches[0];
         }, $long);
         return $that->doc($long, $element, true);
     });
     // Individual annotations processing
     $this->registerHelper('annotation', function ($value, $name, $context) use($that, $generator) {
         switch ($name) {
             case 'param':
             case 'return':
             case 'throws':
                 $description = $that->description($value, $context);
                 return sprintf('<code>%s</code>%s', $that->getTypeLinks($value, $context), $description ? '<br>' . $description : '');
             case 'license':
                 list($url, $description) = $that->split($value);
                 return $that->link($url, $description ?: $url);
             case 'link':
                 list($url, $description) = $that->split($value);
                 if (Nette\Utils\Validators::isUrl($url)) {
                     return $that->link($url, $description ?: $url);
                 }
                 break;
             case 'see':
                 $doc = array();
                 foreach (preg_split('~\\s*,\\s*~', $value) as $link) {
                     if (null !== $generator->resolveElement($link, $context)) {
                         $doc[] = sprintf('<code>%s</code>', $that->getTypeLinks($link, $context));
                     } else {
                         $doc[] = $that->doc($link, $context);
                     }
                 }
                 return implode(', ', $doc);
             case 'uses':
             case 'usedby':
                 list($link, $description) = $that->split($value);
                 $separator = $context instanceof ReflectionClass || !$description ? ' ' : '<br>';
                 if (null !== $generator->resolveElement($link, $context)) {
                     return sprintf('<code>%s</code>%s%s', $that->getTypeLinks($link, $context), $separator, $description);
                 }
                 break;
             default:
                 break;
         }
         // Default
         return $that->doc($value, $context);
     });
     $todo = $this->config->todo;
     $internal = $this->config->internal;
     $this->registerHelper('annotationFilter', function (array $annotations, array $filter = array()) use($todo, $internal) {
         // Filtered, unsupported or deprecated annotations
         static $filtered = array('package', 'subpackage', 'property', 'property-read', 'property-write', 'method', 'abstract', 'access', 'final', 'filesource', 'global', 'name', 'static', 'staticvar');
         foreach ($filtered as $annotation) {
             unset($annotations[$annotation]);
         }
         // Custom filter
         foreach ($filter as $annotation) {
             unset($annotations[$annotation]);
         }
         // Show/hide internal
         if (!$internal) {
             unset($annotations['internal']);
         }
         // Show/hide tasks
         if (!$todo) {
             unset($annotations['todo']);
         }
         return $annotations;
     });
     $this->registerHelper('annotationSort', function (array $annotations) {
         uksort($annotations, function ($one, $two) {
             static $order = array('deprecated' => 0, 'category' => 1, 'copyright' => 2, 'license' => 3, 'author' => 4, 'version' => 5, 'since' => 6, 'see' => 7, 'uses' => 8, 'usedby' => 9, 'link' => 10, 'internal' => 11, 'example' => 12, 'tutorial' => 13, 'todo' => 14);
             if (isset($order[$one], $order[$two])) {
                 return $order[$one] - $order[$two];
             } elseif (isset($order[$one])) {
                 return -1;
             } elseif (isset($order[$two])) {
                 return 1;
             } else {
                 return strcasecmp($one, $two);
             }
         });
         return $annotations;
     });
     $this->registerHelper('annotationBeautify', function ($annotation) {
         static $names = array('usedby' => 'Used by');
         if (isset($names[$annotation])) {
             return $names[$annotation];
         }
         return Nette\Utils\Strings::firstUpper($annotation);
     });
     // Static files versioning
     $destination = $this->config->destination;
     $this->registerHelper('staticFile', function ($name) use($destination) {
         static $versions = array();
         $filename = $destination . DIRECTORY_SEPARATOR . $name;
         if (!isset($versions[$filename]) && is_file($filename)) {
             $versions[$filename] = sprintf('%u', crc32(file_get_contents($filename)));
         }
         if (isset($versions[$filename])) {
             $name .= '?' . $versions[$filename];
         }
         return $name;
     });
     // Source anchors
     $this->registerHelper('sourceAnchors', function ($source) {
         // Classes, interfaces, traits and exceptions
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">(?:class|interface|trait)</span>\\s+)(\\w+)~i', function ($matches) {
             $link = sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]);
             return $matches[1] . $link;
         }, $source);
         // Methods and functions
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">function</span>\\s+)(\\w+)~i', function ($matches) {
             $link = sprintf('<a id="_%1$s" href="#_%1$s">%1$s</a>', $matches[2]);
             return $matches[1] . $link;
         }, $source);
         // Constants
         $source = preg_replace_callback('~(<span class="php-keyword1">const</span>)(.*?)(;)~is', function ($matches) {
             $links = preg_replace_callback('~(\\s|,)([A-Z_]+)(\\s+=)~', function ($matches) {
                 return $matches[1] . sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]) . $matches[3];
             }, $matches[2]);
             return $matches[1] . $links . $matches[3];
         }, $source);
         // Properties
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">(?:private|protected|public|var|static)</span>\\s+)(<span\\s+class="php-var">.*?)(;)~is', function ($matches) {
             $links = preg_replace_callback('~(<span\\s+class="php-var">)(\\$\\w+)~i', function ($matches) {
                 return $matches[1] . sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]);
             }, $matches[2]);
             return $matches[1] . $links . $matches[3];
         }, $source);
         return $source;
     });
     $this->registerHelper('urlize', array($this, 'urlize'));
     $this->registerHelper('relativePath', array($generator, 'getRelativePath'));
     $this->registerHelper('resolveElement', array($generator, 'resolveElement'));
     $this->registerHelper('getClass', array($generator, 'getClass'));
 }
Example #20
0
 /**
  * @param $view
  */
 public function setView($view)
 {
     $this->view = Strings::firstUpper($view);
 }
 /**
  * Capitalize the first word of a string.
  * Also fix the capitalization of WordPress and VersionPress.
  *
  * @param $string
  * @return string
  */
 private function capitalize($string)
 {
     $capitalizedString = Strings::firstUpper($string);
     return str_ireplace(['wordpress', 'versionpress'], ['WordPress', 'VersionPress'], $capitalizedString);
 }
Example #22
0
 /**
  * Creates template.
  *
  * @param \ApiGen\Generator $generator
  * @param \ApiGen\ISourceCodeHighlighter $highlighter
  */
 public function __construct(Generator $generator, ISourceCodeHighlighter $highlighter)
 {
     $this->generator = $generator;
     $this->config = $generator->getConfig();
     // @todo DI
     $this->markup = new MarkdownMarkup($this->config->allowedHtml, $highlighter);
     $that = $this;
     // Output in HTML5
     Nette\Utils\Html::$xhtml = false;
     // Common operations
     $this->registerHelperLoader('Nette\\Templating\\Helpers::loader');
     // PHP source highlight
     $this->registerHelper('highlightPHP', function ($source, $context) use($that, $highlighter) {
         return $that->resolveLink($that->getTypeName($source), $context) ?: $highlighter->highlight((string) $source);
     });
     $this->registerHelper('highlightValue', function ($definition, $context) use($that) {
         return $that->highlightPHP(preg_replace('~^(?:[ ]{4}|\\t)~m', '', $definition), $context);
     });
     // Urls
     $this->registerHelper('packageUrl', new Nette\Callback($this, 'getPackageUrl'));
     $this->registerHelper('namespaceUrl', new Nette\Callback($this, 'getNamespaceUrl'));
     $this->registerHelper('groupUrl', new Nette\Callback($this, 'getGroupUrl'));
     $this->registerHelper('classUrl', new Nette\Callback($this, 'getClassUrl'));
     $this->registerHelper('methodUrl', new Nette\Callback($this, 'getMethodUrl'));
     $this->registerHelper('propertyUrl', new Nette\Callback($this, 'getPropertyUrl'));
     $this->registerHelper('constantUrl', new Nette\Callback($this, 'getConstantUrl'));
     $this->registerHelper('functionUrl', new Nette\Callback($this, 'getFunctionUrl'));
     $this->registerHelper('elementUrl', new Nette\Callback($this, 'getElementUrl'));
     $this->registerHelper('sourceUrl', new Nette\Callback($this, 'getSourceUrl'));
     $this->registerHelper('manualUrl', new Nette\Callback($this, 'getManualUrl'));
     // Packages & namespaces
     $this->registerHelper('packageLinks', new Nette\Callback($this, 'getPackageLinks'));
     $this->registerHelper('namespaceLinks', new Nette\Callback($this, 'getNamespaceLinks'));
     $this->registerHelper('subgroupName', function ($groupName) {
         if ($pos = strrpos($groupName, '\\')) {
             return substr($groupName, $pos + 1);
         }
         return $groupName;
     });
     // Types
     $this->registerHelper('typeLinks', new Nette\Callback($this, 'getTypeLinks'));
     // Docblock descriptions
     $this->registerHelper('description', function ($annotation, $context) use($that) {
         $description = trim(strpbrk($annotation, "\n\r\t \$")) ?: $annotation;
         return $that->doc($description, $context);
     });
     $this->registerHelper('shortDescription', function ($element, $block = false) use($that) {
         return $that->doc($element->getShortDescription(), $element, $block);
     });
     $this->registerHelper('longDescription', function ($element) use($that) {
         $long = $element->getLongDescription();
         // Merge lines
         $long = preg_replace_callback('~(?:<(code|pre)>.+?</\\1>)|([^<]*)~s', function ($matches) {
             return !empty($matches[2]) ? preg_replace('~\\n(?:\\t|[ ])+~', ' ', $matches[2]) : $matches[0];
         }, $long);
         return $that->doc($long, $element, true);
     });
     // Individual annotations processing
     $this->registerHelper('annotation', function ($value, $name, Reflection\ReflectionElement $context) use($that, $generator) {
         switch ($name) {
             case 'return':
             case 'throws':
                 // TODO: Needs fix - This produces duplicate throws statements
                 //					$description = $that->description($value, $context);
                 //					return sprintf('<code>%s</code>%s', $that->getTypeLinks($value, $context), $description ? '<br>' . $description : '');
                 return $that->getTypeLinks($value, $context);
             case 'license':
                 list($url, $description) = $that->split($value);
                 return $that->link($url, $description ?: $url);
             case 'link':
                 list($url, $description) = $that->split($value);
                 if (Nette\Utils\Validators::isUrl($url)) {
                     return $that->link($url, $description ?: $url);
                 }
                 break;
             case 'see':
                 $doc = array();
                 foreach (preg_split('~\\s*,\\s*~', $value) as $link) {
                     if (null !== $generator->resolveElement($link, $context)) {
                         $doc[] = sprintf('<code>%s</code>', $that->getTypeLinks($link, $context));
                     } else {
                         $doc[] = $that->doc($link, $context);
                     }
                 }
                 return implode(', ', $doc);
             case 'uses':
             case 'usedby':
                 list($link, $description) = $that->split($value);
                 $separator = $context instanceof Reflection\ReflectionClass || !$description ? ' ' : '<br>';
                 if (null !== $generator->resolveElement($link, $context)) {
                     return sprintf('<code>%s</code>%s%s', $that->getTypeLinks($link, $context), $separator, $description);
                 }
                 break;
             default:
                 break;
         }
         // Default
         return $that->doc($value, $context);
     });
     $todo = $this->config->todo;
     $internal = $this->config->internal;
     $this->registerHelper('annotationFilter', function (array $annotations, array $filter = array()) use($todo, $internal) {
         // Filtered, unsupported or deprecated annotations
         static $filtered = array('package', 'subpackage', 'property', 'property-read', 'property-write', 'method', 'abstract', 'access', 'final', 'filesource', 'global', 'name', 'static', 'staticvar');
         foreach ($filtered as $annotation) {
             unset($annotations[$annotation]);
         }
         // Custom filter
         foreach ($filter as $annotation) {
             unset($annotations[$annotation]);
         }
         // Show/hide internal
         if (!$internal) {
             unset($annotations['internal']);
         }
         // Show/hide tasks
         if (!$todo) {
             unset($annotations['todo']);
         }
         return $annotations;
     });
     $this->registerHelper('annotationSort', function (array $annotations) {
         uksort($annotations, function ($one, $two) {
             static $order = array('deprecated' => 0, 'category' => 1, 'copyright' => 2, 'license' => 3, 'author' => 4, 'version' => 5, 'since' => 6, 'see' => 7, 'uses' => 8, 'usedby' => 9, 'link' => 10, 'internal' => 11, 'example' => 12, 'tutorial' => 13, 'todo' => 14);
             if (isset($order[$one], $order[$two])) {
                 return $order[$one] - $order[$two];
             } elseif (isset($order[$one])) {
                 return -1;
             } elseif (isset($order[$two])) {
                 return 1;
             } else {
                 return strcasecmp($one, $two);
             }
         });
         return $annotations;
     });
     $this->registerHelper('annotationBeautify', function ($annotation) {
         static $names = array('usedby' => 'Used by');
         if (isset($names[$annotation])) {
             return $names[$annotation];
         }
         return Nette\Utils\Strings::firstUpper($annotation);
     });
     // Static files versioning
     $destination = $this->config->destination;
     $this->registerHelper('staticFile', function ($name) use($destination) {
         static $versions = array();
         $filename = $destination . DIRECTORY_SEPARATOR . $name;
         if (!isset($versions[$filename]) && is_file($filename)) {
             $versions[$filename] = sprintf('%u', crc32(file_get_contents($filename)));
         }
         if (isset($versions[$filename])) {
             $name .= '?' . $versions[$filename];
         }
         return $name;
     });
     // Source anchors
     $this->registerHelper('sourceAnchors', function ($source) {
         // Classes, interfaces, traits and exceptions
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">(?:class|interface|trait)</span>\\s+)(\\w+)~i', function ($matches) {
             $link = sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]);
             return $matches[1] . $link;
         }, $source);
         // Methods and functions
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">function</span>\\s+)(\\w+)~i', function ($matches) {
             $link = sprintf('<a id="_%1$s" href="#_%1$s">%1$s</a>', $matches[2]);
             return $matches[1] . $link;
         }, $source);
         // Constants
         $source = preg_replace_callback('~(<span class="php-keyword1">const</span>)(.*?)(;)~is', function ($matches) {
             $links = preg_replace_callback('~(\\s|,)([A-Z_]+)(\\s+=)~', function ($matches) {
                 return $matches[1] . sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]) . $matches[3];
             }, $matches[2]);
             return $matches[1] . $links . $matches[3];
         }, $source);
         // Properties
         $source = preg_replace_callback('~(<span\\s+class="php-keyword1">(?:private|protected|public|var|static)</span>\\s+)(<span\\s+class="php-var">.*?)(;)~is', function ($matches) {
             $links = preg_replace_callback('~(<span\\s+class="php-var">)(\\$\\w+)~i', function ($matches) {
                 return $matches[1] . sprintf('<a id="%1$s" href="#%1$s">%1$s</a>', $matches[2]);
             }, $matches[2]);
             return $matches[1] . $links . $matches[3];
         }, $source);
         return $source;
     });
     $this->registerHelper('urlize', array($this, 'urlize'));
     $this->registerHelper('relativePath', array($generator, 'getRelativePath'));
     $this->registerHelper('resolveElement', array($generator, 'resolveElement'));
     $this->registerHelper('getClass', array($generator, 'getClass'));
 }
 /**
  * Akce pro přesměrování na správnou akci pro definici nového preprocessingu
  * @param int $miner
  * @param int $column
  * @param string $type
  */
 public function actionNewPreprocessing($miner, $column, $type)
 {
     $this->redirect('newPreprocessing' . Strings::firstUpper($type), ['miner' => $miner, 'column' => $column]);
 }
Example #24
0
 public function processGetters()
 {
     $arr = [];
     foreach (Arrays::get($this->data, 'variables', []) as $name => $vars) {
         $g1 = Arrays::get((array) $vars, 'getter', TRUE);
         $g2 = Arrays::get((array) $vars, 'auto', TRUE);
         if ($g2 !== FALSE && $g1 !== FALSE) {
             if (is_numeric($name)) {
                 $name = $vars;
                 $vars = NULL;
             }
             $arr[] = $this->getVisibility($vars) . "function get" . Strings::firstUpper($name) . "(\${$name}){\n\t\treturn \$this->{$name};\n\t}\n";
         }
     }
     $this->template->getters = $arr;
 }
Example #25
0
 /**
  * @param string $tableName
  * @param array $columns
  * @return void
  */
 protected function generateTableGeneratedHyperSelection($tableName, $columns)
 {
     $classFqn = $this->config['classes']['selection']['generated'];
     $classFqn = Helpers::substituteClassWildcard($classFqn, $tableName);
     $className = Helpers::extractClassName($classFqn);
     $classNamespace = Helpers::extractNamespace($classFqn);
     $extendsFqn = $this->config['classes']['selection']['base'];
     $extends = Helpers::formatClassName($extendsFqn, $classNamespace);
     $class = new ClassType($className);
     $class->setExtends($extends);
     // Add annotations for methods returning specific row class
     $correspondingHyperRowTableClass = $this->getTableClass('row', $tableName, $classNamespace);
     $correspondingHyperSelectionTableClass = $this->getTableClass('selection', $tableName, $classNamespace);
     $methods = ['fetch()' => $correspondingHyperRowTableClass . '|FALSE', 'get($key)' => $correspondingHyperRowTableClass . '|FALSE', 'current()' => $correspondingHyperRowTableClass . '|FALSE', 'select($columns)' => $correspondingHyperSelectionTableClass, 'where($condition, $parameters = [])' => $correspondingHyperSelectionTableClass, 'wherePrimary($key)' => $correspondingHyperSelectionTableClass, 'group($columns)' => $correspondingHyperSelectionTableClass, 'having($having)' => $correspondingHyperSelectionTableClass, 'insert($data)' => $correspondingHyperRowTableClass, 'fetchAll()' => $correspondingHyperRowTableClass . '[]', 'order($columns)' => $correspondingHyperSelectionTableClass, 'limit($limit, $offset = NULL)' => $correspondingHyperSelectionTableClass, 'page($page, $itemsPerPage, & $numOfPages = NULL)' => $correspondingHyperSelectionTableClass, 'offsetGet($key)' => $correspondingHyperRowTableClass];
     foreach ($methods as $methodName => $returnType) {
         $class->addComment("@method {$returnType} {$methodName}");
     }
     // Generate methods.selection.where
     foreach ((array) $this->config['methods']['selection']['where'] as $methodTemplate) {
         // Add where methods based on columns
         foreach ($columns as $column => $type) {
             // withFuture*, withPast*
             if (in_array($type, [IStructure::FIELD_DATETIME, IStructure::FIELD_UNIX_TIMESTAMP])) {
                 $methodName = Helpers::substituteMethodWildcard($methodTemplate, 'Future' . Strings::firstUpper($column));
                 $method = $class->addMethod($methodName);
                 $method->addBody("return \$this->where('{$column} > NOW()');");
                 $method->addComment("@return {$correspondingHyperSelectionTableClass}");
                 $methodName = Helpers::substituteMethodWildcard($methodTemplate, 'Past' . Strings::firstUpper($column));
                 $method = $class->addMethod($methodName);
                 $method->addBody("return \$this->where('{$column} < NOW()');");
                 $method->addComment("@return {$correspondingHyperSelectionTableClass}");
             }
             if (in_array($type, [IStructure::FIELD_DATETIME, IStructure::FIELD_TIME, IStructure::FIELD_DATE, IStructure::FIELD_UNIX_TIMESTAMP])) {
                 $type = '\\Nette\\Utils\\DateTime';
             }
             $methodName = Helpers::substituteMethodWildcard($methodTemplate, $column);
             $method = $class->addMethod($methodName);
             if ($type == 'bool') {
                 $method->addParameter('value', 'TRUE');
             } else {
                 $method->addParameter('value');
             }
             $method->addBody('return $this->where(?, $value);', [$column]);
             $method->addComment("@param {$type} \$value");
             $method->addComment("@return {$correspondingHyperSelectionTableClass}");
         }
     }
     // generate methods.selection.whereRelated
     foreach ((array) $this->config['methods']['selection']['whereRelated'] as $methodTemplate) {
         // Generate methods
         foreach ($this->structure->getHasManyReference($tableName) as $relatedTable => $referencingColumns) {
             // Check excluded tables
             if (is_array($this->config['tables']) && !in_array($relatedTable, $this->config['tables'])) {
                 continue;
             }
             foreach ($referencingColumns as $referencingColumn) {
                 // Omit longest common prefix between $relatedTable and (this) $tableName
                 $result = Helpers::underscoreToCamelWithoutPrefix($relatedTable, $tableName);
                 // Discover suffix if any
                 if (count($referencingColumns) > 1) {
                     $suffix = 'As' . Helpers::underscoreToCamel(Strings::replace($referencingColumn, '~_id$~'));
                 } else {
                     $suffix = NULL;
                 }
                 $methodName = Helpers::substituteMethodWildcard($methodTemplate, $result, $suffix);
                 $returnType = $correspondingHyperSelectionTableClass;
                 $parameterName = Strings::firstLower(Helpers::underscoreToCamel($relatedTable)) . 'Id';
                 $method = $class->addMethod($methodName);
                 $method->addParameter($parameterName);
                 $method->addBody("return \$this->where(':{$relatedTable}({$referencingColumn}).id', \$?);", [$parameterName])->addComment("@return {$returnType}");
                 // Add property annotations
                 if (Strings::startsWith($methodName, 'get')) {
                     $property = Strings::firstLower(Strings::substring($methodName, 3));
                     $class->addComment("@property-read {$returnType} \${$property}");
                 }
             }
         }
     }
     // generate methods.selection.whereRelatedWith
     foreach ((array) $this->config['methods']['selection']['whereRelatedWith'] as $methodTemplate) {
         // Generate methods
         foreach ($this->structure->getHasManyReference($tableName) as $relatedTable => $referencingColumns) {
             // Check excluded tables
             if (is_array($this->config['tables']) && !in_array($relatedTable, $this->config['tables'])) {
                 continue;
             }
             foreach ($referencingColumns as $referencingColumn) {
                 //                    if ($tableName == 'tag') {
                 //                        dump($tableName); // author | tag (M:N)
                 //                        dump($relatedTable); // book | book_tagging (M:N)
                 //                        dump($referencingColumns); // [author_id, translator_id] | [tag_id]
                 //                        // related (on 1:N): relatedBooksAsAuthor, relatedBooksAsTranslator - result BookSelection
                 //                        // whereRelated (on 1:N): inBook(bookId), inBookAsAuthor(bookId), inBookAsTranslator(bookId)
                 //
                 //                        // whereRelated (on M:N): inTaggingWithBook(As...)(bookId)
                 //
                 //                        $furtherReferences = $this->structure->getBelongsToReference($relatedTable);
                 //                        unset($furtherReferences[$referencingColumn]);
                 //                        dump($furtherReferences);
                 //
                 //                        if (Strings::startsWith($relatedTable, $tableName)) {
                 //                            dump('TRUE');
                 //                        }
                 //                    }
                 foreach ($this->structure->getBelongsToReference($relatedTable) as $furtherReferencingColumn => $furtherReferencedTable) {
                     // Do not return where I came from
                     if ($furtherReferencingColumn == $referencingColumn) {
                         continue;
                     }
                     if (!Strings::endsWith($relatedTable, 'ing') && in_array($methodTemplate, ['*', 'get*'])) {
                         continue;
                     }
                     // Omit longest common prefix between $relatedTable and (this) $tableName
                     $relatedTableResult = Helpers::underscoreToCamelWithoutPrefix($relatedTable, $tableName);
                     $end = NULL;
                     if (Strings::endsWith($relatedTable, 'ing') && in_array($methodTemplate, ['*', 'get*'])) {
                         // TODO problem:
                         // couse_tagging, couse
                         // couse_tagging, course_tag
                         if (Strings::startsWith($relatedTable, $tableName)) {
                             // taggedByBook
                             $relatedTableResult = Strings::replace($relatedTableResult, '~ing$~', 'ed');
                             // Add 'With' suffix (not configurable in method template - 2 * needed for that (TODO))
                             $end = 'By' . Helpers::underscoreToCamelWithoutPrefix(Strings::replace($furtherReferencingColumn, '~_id$~'), $tableName);
                         } else {
                             // taggingBook
                             // Omit longest common prefix between $relatedTable and (this) $tableName
                             $relatedTableResult = Helpers::underscoreToCamelWithoutPrefix($relatedTable, $furtherReferencedTable);
                             $end = Helpers::underscoreToCamelWithoutPrefix(Strings::replace($furtherReferencingColumn, '~_id$~'), $tableName);
                         }
                     } else {
                         // Add 'With' suffix (not configurable in method template - 2 * needed for that (TODO))
                         $end = 'With' . Helpers::underscoreToCamelWithoutPrefix(Strings::replace($furtherReferencingColumn, '~_id$~'), $tableName);
                     }
                     //                        if ($tableName == 'tag') {
                     //                            dump($relatedTableResult);
                     //                        }
                     // Discover 'As' suffix if any
                     $suffix = NULL;
                     if (count($referencingColumns) > 1) {
                         $suffix = 'As' . Helpers::underscoreToCamel(Strings::replace($referencingColumn, '~_id$~'));
                     }
                     $methodName = Helpers::substituteMethodWildcard($methodTemplate, $relatedTableResult, $suffix || $end ? $suffix . $end : NULL);
                     $returnType = $correspondingHyperSelectionTableClass;
                     $parameterName = Strings::firstLower(Helpers::underscoreToCamelWithoutPrefix(Strings::replace($furtherReferencingColumn, '~_id$~'), $tableName)) . 'Id';
                     $method = $class->addMethod($methodName);
                     $method->addParameter($parameterName);
                     $method->addBody("return \$this->where(':{$relatedTable}({$referencingColumn}).{$furtherReferencingColumn}', \$?);", [$parameterName])->addComment("@return {$returnType}");
                     // Add property annotations
                     if (Strings::startsWith($methodName, 'get')) {
                         $property = Strings::firstLower(Strings::substring($methodName, 3));
                         $class->addComment("@property-read {$returnType} \${$property}");
                     }
                 }
             }
         }
     }
     $code = implode("\n\n", ['<?php', "/**\n * This is a generated file. DO NOT EDIT. It will be overwritten.\n */", "namespace {$classNamespace};", $class]);
     $dir = $this->config['dir'] . '/' . 'tables' . '/' . $tableName;
     $file = $dir . '/' . $className . '.php';
     $this->writeIfChanged($file, $code);
 }
Example #26
0
 /**
  * Get action name 
  * @param  string $method   
  * @param  array $arguments 
  * @return string
  */
 private function getActionName($method, $arguments)
 {
     if (!isset($this->methods[$method])) {
         throw new InvalidArgumentException('Reuqest method must be one of ' . join(', ', array_keys($this->methods)) . ', ' . $method . ' given');
     }
     $name = $this->methods[$method];
     for ($i = 0, $count = count($arguments); $i < $count; $i += 2) {
         $name += Strings::firstUpper($arguments[$i]);
     }
     return $name;
 }
Example #27
0
 protected function getTemplate($name)
 {
     return __DIR__ . '/' . Strings::firstUpper($this->shop) . '/latte/' . $name . '.latte';
 }
Example #28
0
 /**
  * @param string $name String with * in it
  * @param string $substitution
  * @return string
  */
 public static function substituteClassWildcard($name, $substitution)
 {
     $substitution = self::underscoreToCamel($substitution);
     $substitution = Strings::firstUpper($substitution);
     return Strings::replace($name, '#\\*#', $substitution);
 }
Example #29
0
 private function countMinus()
 {
     $randNum1 = array_rand($this->numbers);
     $randNum2 = array_rand($this->numbers);
     if ($randNum1 > $randNum2) {
         $max = $randNum1;
         $min = $randNum2;
     } else {
         $max = $randNum2;
         $min = $randNum1;
     }
     $res = $max - $min;
     return [Strings::firstUpper($this->numbers[$max]) . ' mínus ' . $this->numbers[$min] . ' se rovná ', $res, ''];
 }