예제 #1
1
 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  */
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = [];
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
예제 #2
0
 /**
  * Format text column cell
  * @param mixed $value
  * @param mixed $rowData
  * @return mixed|string
  */
 public function render($value, $rowData)
 {
     $value = parent::render($value, $rowData);
     // Truncate content
     $value = $this->maxLength > 0 ? Strings::truncate($value, $this->maxLength) : $value;
     return $value;
 }
예제 #3
0
파일: PathSelect.php 프로젝트: ixtrum/forms
 /**
  * Generate dir structure tree
  *
  * @param string  $dir       Path to root dir
  * @param boolean $showFiles Show files
  *
  * @return \Nette\Utils\Html
  */
 private function generateTree($dir, $showFiles = true)
 {
     if (!is_dir($dir)) {
         throw new \Exception("Directory '{$dir}' does not exist!");
     }
     if ($showFiles) {
         $files = Finder::find("*")->in($dir);
     } else {
         $files = Finder::findDirectories("*")->in($dir);
     }
     $list = Html::el("ul");
     foreach ($files as $file) {
         // Create file link
         $link = Html::el("a")->href($file->getRealPath())->title($file->getRealPath());
         if ($file->isDir()) {
             $link[0] = Html::el("i")->class("icon-folder-open");
         } else {
             $link[0] = Html::el("i")->class("icon-file");
         }
         $link[1] = Html::el("span", Strings::truncate($file->getFileName(), 30));
         // Create item in list
         $item = Html::el("li");
         $item[0] = $link;
         if ($file->isDir()) {
             $item[1] = $this->generateTree($file->getPathName(), $showFiles);
         }
         $list->add($item);
     }
     return $list;
 }
예제 #4
0
파일: Text.php 프로젝트: pepakriz/grido
 /**
  * @param string $maxLen UTF-8 encoding
  * @param string $append UTF-8 encoding
  * @return Column
  */
 public function setTruncate($maxLen, $append = "…")
 {
     $this->truncate = function ($string) use($maxLen, $append) {
         return \Nette\Utils\Strings::truncate($string, $maxLen, $append);
     };
     return $this;
 }
예제 #5
0
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = array();
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     $items = $this->items;
     $nestedKeys = array();
     array_walk_recursive($items, function ($value, $key) use(&$nestedKeys) {
         $nestedKeys[] = $key;
     });
     if ($diff = array_diff($values, $nestedKeys)) {
         $range = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, $nestedKeys)), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed range [{$range}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
예제 #6
0
 /**
  * Formats cell's content.
  * @param  mixed
  * @param  \DibiRow|array
  * @return string
  */
 public function formatContent($value, $data = NULL)
 {
     $value = htmlSpecialChars($value);
     if (is_array($this->replacement) && !empty($this->replacement)) {
         if (in_array($value, array_keys($this->replacement))) {
             $value = $this->replacement[$value];
         }
     }
     foreach ($this->formatCallback as $callback) {
         if (is_callable($callback)) {
             $value = call_user_func($callback, $value, $data);
         }
     }
     // translate & truncate
     if ($value instanceof Nette\Utils\Html) {
         $text = $this->dataGrid->translate($value->getText());
         if ($this->maxLength != 0) {
             $text = Nette\Utils\Strings::truncate($text, $this->maxLength);
         }
         $value->setText($text);
         $value->title = $this->dataGrid->translate($value->title);
     } else {
         if ($this->maxLength != 0) {
             $value = Nette\Utils\Strings::truncate($value, $this->maxLength);
         }
     }
     return $value;
 }
예제 #7
0
 public function renderDefault()
 {
     $trips = $this->mapModel->loadTrips($this->user->id);
     $categories = $this->mapModel->loadCategories($this->user->id);
     $newTrips = [];
     foreach ($trips as $trip) {
         //            if ($trip->duration == 1) {
         //                $duration = $trip->duration.' den';
         //            } elseif ($trip->duration < 5) {
         //                $duration = $trip->duration.' dny';
         //            } else {
         //                $duration = $trip->duration.' dní';
         //            }
         if ($trip->category_id) {
             $color = ['red' => $categories[$trip->category_id]->red, 'green' => $categories[$trip->category_id]->green, 'blue' => $categories[$trip->category_id]->blue];
         } else {
             $color = ['red' => 0, 'green' => 0, 'blue' => 0];
         }
         $lol = Utils\Strings::truncate($trip->name, 20);
         $newTrips[] = ['id' => $trip->id, 'polygon' => $trip->polygon, 'color' => $color, 'info' => ['name' => $trip->name, 'date' => $trip->date->format('d. m. Y'), 'length' => $trip->lenght, 'duration' => $trip->duration, 'text' => $trip->text, 'category' => $trip->category_id ? $categories[$trip->category_id]->name : NULL, 'categoryId' => $trip->category_id ? $trip->category_id : NULL]];
     }
     $this->template->trips = $newTrips;
     $this->template->showModal = FALSE;
     $this['newTripForm']->setDefaults(['name' => ' ', 'text' => ' ', 'lenght' => ' ']);
     $this->redrawControl("newTrip");
 }
예제 #8
0
 /**
  * Truncate value to $max character and return string or null
  *
  * @param string  $value
  * @param integer $max
  *
  * @return string|null
  */
 protected function StringTruncate($value, $max = 255)
 {
     if ($value) {
         return (string) Strings::truncate($value, $max, "");
     } else {
         return null;
     }
 }
예제 #9
0
    public function getPanel()
    {
        $this->disabled = TRUE;
        $s = '';
        $h = 'htmlSpecialChars';
        foreach ($this->queries as $i => $query) {
            list($sql, $params, $time, $rows, $connection, $source) = $query;
            $explain = NULL;
            // EXPLAIN is called here to work SELECT FOUND_ROWS()
            if ($this->explain && preg_match('#\\s*\\(?\\s*SELECT\\s#iA', $sql)) {
                try {
                    $cmd = is_string($this->explain) ? $this->explain : 'EXPLAIN';
                    $explain = $connection->queryArgs("{$cmd} {$sql}", $params)->fetchAll();
                } catch (\PDOException $e) {
                }
            }
            $s .= '<tr><td>' . sprintf('%0.3f', $time * 1000);
            if ($explain) {
                static $counter;
                $counter++;
                $s .= "<br /><a href='#' class='nette-toggler' rel='#nette-DbConnectionPanel-row-{$counter}'>explain&nbsp;&#x25ba;</a>";
            }
            $s .= '</td><td class="nette-DbConnectionPanel-sql">' . Helpers::dumpSql(self::$maxLength ? Nette\Utils\Strings::truncate($sql, self::$maxLength) : $sql);
            if ($explain) {
                $s .= "<table id='nette-DbConnectionPanel-row-{$counter}' class='nette-collapsed'><tr>";
                foreach ($explain[0] as $col => $foo) {
                    $s .= "<th>{$h($col)}</th>";
                }
                $s .= "</tr>";
                foreach ($explain as $row) {
                    $s .= "<tr>";
                    foreach ($row as $col) {
                        $s .= "<td>{$h($col)}</td>";
                    }
                    $s .= "</tr>";
                }
                $s .= "</table>";
            }
            if ($source) {
                $s .= Nette\Diagnostics\Helpers::editorLink($source[0], $source[1])->class('nette-DbConnectionPanel-source');
            }
            $s .= '</td><td>';
            foreach ($params as $param) {
                $s .= Debugger::dump($param, TRUE);
            }
            $s .= '</td><td>' . $rows . '</td></tr>';
        }
        return empty($this->queries) ? '' : '<style> #nette-debug td.nette-DbConnectionPanel-sql { background: white !important }
			#nette-debug .nette-DbConnectionPanel-source { color: #BBB !important }
			#nette-debug nette-DbConnectionPanel tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>
			<h1>Queries: ' . count($this->queries) . ($this->totalTime ? ', time: ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms' : '') . '</h1>
			<div class="nette-inner nette-DbConnectionPanel">
			<table>
				<tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Params</th><th>Rows</th></tr>' . $s . '
			</table>
			</div>';
    }
예제 #10
0
	/**
	 * Sets selected item (by key).
	 * @param  scalar
	 * @return self
	 */
	public function setValue($value)
	{
		if ($value !== NULL && !array_key_exists((string) $value, $this->items)) {
			$set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) { return var_export($s, TRUE); }, array_keys($this->items))), 70, '...');
			throw new Nette\InvalidArgumentException("Value '$value' is out of allowed set [$set] in field '{$this->name}'.");
		}
		$this->value = $value === NULL ? NULL : key(array((string) $value => NULL));
		return $this;
	}
예제 #11
0
파일: Macro.php 프로젝트: bazo/Tatami
 private static function parseMedia($word)
 {
     $parts = explode(':\'', $word);
     if (!isset($parts[1])) {
         $parts = explode(':"', $word);
     }
     $media = $parts[1];
     $media = Strings::truncate($media, strlen($media) - 1, null);
     return $media;
 }
예제 #12
0
 public function getArticles($menuId, $fullArticleId = NULL)
 {
     $sql = "SELECT a.id,[text] AS html FROM article a\n\t\t\tJOIN name_has_text nht ON a.name_id=nht.name_id AND language_id=%i\n\t\t\tJOIN text t ON t.id=nht.text_id\n\t\t\tWHERE menu_id=%i\n\t\t\tORDER BY a.sort ASC,a.id DESC";
     $rows = $this->db->query($sql, $this->getLanguageId(), $menuId)->fetchAll();
     foreach ($rows as &$row) {
         if ($row['id'] != $fullArticleId) {
             $row['html'] = strip_tags($row['html'], '<h2>');
             $row['html'] = \Nette\Utils\Strings::truncate($row['html'], 1024);
         }
     }
     return $rows;
 }
 /**
  * @param \NetteAddons\Model\Importers\IAddonVersionsImporter
  * @param string
  * @param int
  */
 private function processUpdate(IAddonVersionsImporter $addonVersionImporter, $url, $id)
 {
     try {
         $this->db->beginTransaction();
         $addon = $addonVersionImporter->getAddon($url);
         /** @var \Nette\Database\Table\ActiveRow $row */
         $row = $this->db->table('addons')->get($id);
         if (!$row) {
             $this->db->rollBack();
             return;
         }
         $row->update(array('composerVendor' => $addon->getComposerVendor(), 'composerName' => $addon->getComposerName(), 'shortDescription' => Strings::truncate($addon->getPerex(), 250), 'stars' => $addon->getStars()));
         $this->db->table('addons_versions')->where('addonId = ?', $id)->delete();
         $row = $this->db->table('addons_resources')->where('addonId = ? AND type = ?', $id, AddonResources::RESOURCE_PACKAGIST)->fetch();
         if ($row) {
             if ($addon->getPackagist() === null) {
                 $row->delete();
             } else {
                 $row->update(array('resource' => $addon->getPackagist()));
             }
         } elseif ($addon->getPackagist() !== null) {
             $this->db->table('addons_resources')->insert(array('addonId' => $id, 'type' => AddonResources::RESOURCE_PACKAGIST, 'resource' => $addon->getPackagist()));
         }
         $row = $this->db->table('addons_resources')->where('addonId = ? AND type = ?', $id, AddonResources::RESOURCE_GITHUB)->fetch();
         if ($row) {
             if ($addon->getGithub() === null) {
                 $row->delete();
             } else {
                 $row->update(array('resource' => $addon->getGithub()));
             }
         } elseif ($addon->getGithub() !== null) {
             $this->db->table('addons_resources')->insert(array('addonId' => $id, 'type' => AddonResources::RESOURCE_GITHUB, 'resource' => $addon->getGithub()));
         }
         foreach ($addon->getVersions() as $version) {
             /** @var \Nette\Database\Table\ActiveRow $row */
             $row = $this->db->table('addons_versions')->insert(array('addonId' => $id, 'version' => $version->getVersion(), 'license' => implode(', ', $version->getLicenses()), 'distType' => 'zip', 'distUrl' => 'https://nette.org', 'updatedAt' => new DateTime(), 'composerJson' => ''));
             if (!$row) {
                 $this->db->rollBack();
                 return;
             }
             foreach ($version->getDependencies() as $dependency) {
                 // @todo addon link
                 $this->db->table('addons_dependencies')->insert(array('versionId' => $row->id, 'packageName' => $dependency->getDependencyName(), 'version' => $dependency->getDependencyVersion(), 'type' => $dependency->getType()));
             }
         }
         $this->db->commit();
     } catch (\Exception $e) {
         Debugger::log($e);
         $this->db->rollBack();
     }
 }
예제 #14
0
 public function addNewQueries($description, $queries)
 {
     // create new file and save queries there
     $time = time();
     $filename = $time . '_' . Strings::webalize(Strings::truncate($description, 30)) . '.sql';
     file_put_contents($this->changelogPath . $filename, $queries);
     // save queries into database table changelog
     $queries = explode(';', $queries);
     foreach ($queries as $query) {
         $query = trim($query);
         if (empty($query)) {
             continue;
         }
         $data = array('file' => $filename, 'description' => $description, 'query' => $query, 'executed' => 1, 'ins_timestamp' => $time, 'ins_dt' => new \DateTime(), 'ins_process_id' => 'DbChangelog::addNewQueries');
         $this->changelogTable->insert($data);
     }
     return TRUE;
 }
예제 #15
0
 protected function configure($presenter)
 {
     $this->selection->select("error.id, title, message, error_dt, project_id.name AS project_name, error_status_id.status AS status");
     $source = new \NiftyGrid\DataSource\NDataSource($this->selection);
     $self = $this;
     $this->setDataSource($source);
     $this->setDefaultOrder("error_dt DESC");
     $this->addColumn("project_name", "Project")->setTableName("project_id")->setSortable()->setSelectFilter($this->projectEntity->findAll()->fetchPairs("id", "name"));
     $this->addColumn("title", "Title")->setTextFilter()->setSortable();
     $this->addColumn("message", "Message")->setSortable()->setTextFilter()->setRenderer(function ($row) use($presenter) {
         return \Nette\Utils\Html::el("a")->setText(trim($row["message"]) ? Strings::truncate($row["message"], 60) : $row["id"])->addAttributes(array("target" => "_blank"))->href($presenter->link("ErrorList:display", $row["id"]));
     });
     $this->addColumn("status", "Status")->setTableName("error_status_id")->setSelectFilter($this->lstErrorStatus->findAll()->fetchPairs("id", "status"))->setRenderer(function ($row) use($presenter) {
         $label = "";
         if ($row["status"] == "New") {
             $label = "label-important";
         }
         return \Nette\Utils\Html::el("span")->setText($row["status"])->addAttributes(array("class" => "label {$label}"));
     });
     if (!isset($this->filter['status'])) {
         $this->filter['status'] = '1';
     }
     $this->addColumn("error_dt", "Date", "150px")->setDateFilter()->setSortable()->setRenderer(function ($row) {
         return $row["error_dt"]->format("j.n.Y H:i:s");
     });
     $this->addButton("archive", "Archive")->setText("Archive")->setAjax()->setLink(function ($row) use($presenter) {
         return $presenter->link("archive!", $row['id']);
     })->setClass("btn-success btn-solve");
     /*
     		$this->addButton("createTask", "Create Task")
     			->setText('Create task')
     			->setAjax()
     			->setLink(function($row) use ($presenter){return $presenter->link("createTask!", $row['id']);})
     			->setClass("btn-info");
     */
     $this->addAction("archive", "Archive")->setAjax(true)->setCallback(function ($selectedItems) use($self) {
         $self->handleArchive($selectedItems);
     });
     $this->addAction("unarchive", "Unarchive")->setAjax(true)->setCallback(function ($selectedItems) use($self) {
         $self->handleUnArchive($selectedItems);
     });
 }
 /**
  * Imports addon from GitHub repository.
  *
  * @return \NetteAddons\Model\Addon
  * @throws \NetteAddons\IOException
  */
 public function import()
 {
     $info = $this->repository->getMetadata();
     if (!isset($info->default_branch, $info->name, $info->description)) {
         throw new \NetteAddons\IOException('GitHub returned invalid response.');
     }
     $readme = $this->repository->getReadme($info->default_branch);
     $composer = $this->getComposerJson($info->default_branch);
     $addon = new Addon();
     // name
     $addon->name = $info->name;
     // composerName
     if ($composer && $this->validators->isComposerFullNameValid($composer->name)) {
         $addon->composerFullName = $composer->name;
     }
     // shortDescription
     if ($composer) {
         $addon->shortDescription = Strings::truncate($composer->description, 250);
     } elseif (!empty($info->description)) {
         $addon->shortDescription = Strings::truncate($info->description, 250);
     }
     // description
     if ($readme) {
         $addon->description = $readme->content;
         $ext = strtolower(pathinfo($readme->path, PATHINFO_EXTENSION));
         $addon->descriptionFormat = in_array($ext, array('md', 'markdown')) ? 'markdown' : 'texy';
     }
     // default license
     if ($composer && isset($composer->license)) {
         $addon->defaultLicense = implode(',', (array) $composer->license);
     }
     // repository
     $addon->repository = $this->repository->getUrl();
     $addon->repositoryHosting = 'github';
     // tags
     if ($composer && isset($composer->keywords)) {
         $addon->tags = $composer->keywords;
     }
     return $addon;
 }
예제 #17
0
 protected function createComponentInterpretList($name)
 {
     $grid = new Grid($this, $name);
     $grid->setModel($this->interpreti->findAll());
     $grid->addColumnText("nazev", "Interpret")->setCustomRender(function ($item) {
         return !$item->interpret_id ? Html::el('b')->setText($item->nazev) : $item->nazev;
     })->setSortable()->setFilterText()->setSuggestion();
     $grid->addColumnText("alias", "Alias pro")->setColumn(function ($item) {
         return isset($item->interpret->nazev) ? $item->interpret->nazev : null;
     });
     $grid->addFilterCheck('interpret_id', 'Jen aliasy');
     $grid->addColumnText("desc", "Popis")->setCustomRender(function ($item) {
         return Strings::truncate($item->desc, 256);
     });
     $grid->addActionHref('edit', 'Editovat', 'editor')->setIcon('pencil');
     $grid->addActionHref('delete', 'Smazat', 'delete!')->setIcon('trash')->setConfirm('Opravdu chcete smazat tohoto interpreta?');
     //Set face for grid
     $gridTemplate = __DIR__ . "/../templates/components/Grid.latte";
     if (file_exists($gridTemplate)) {
         $grid->setTemplateFile($gridTemplate);
     }
     return $grid;
 }
예제 #18
0
    /**
     * Renders HTML code for custom panel.
     * @return string
     */
    public function getPanel()
    {
        $s = '';
        $h = 'htmlSpecialChars';
        foreach ($this->queries as $query) {
            $s .= '<tr><td>' . sprintf('%0.3f', $query->time * 1000000) . '</td>';
            $s .= '<td class="neo4j-query">' . $h(self::$maxLength ? Nette\Utils\Strings::truncate($query->query, self::$maxLength) : $query->query) . '</td>';
            $parameters = '';
            foreach ($query->parameters as $key => $value) {
                $parameters .= $key . ': ' . $value . "\n";
            }
            $s .= '<td>' . $parameters . '</td>';
            $s .= '<td>' . $query->results . '</td>';
            $s .= '</tr>';
        }
        return empty($this->queries) ? '' : '<style> #nette-debug div.neo4j-panel table td { text-align: right }
			#nette-debug div.neo4j-panel table td.neo4j-query { background: white !important; text-align: left } </style>
			<h1>Queries: ' . count($this->queries) . ($this->totalTime ? ', time: ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms' : '') . '</h1>
			<div class="nette-inner neo4j-panel">
			<table>
				<tr><th>Time&nbsp;µs</th><th>Query</th><th>Parameters</th><th>Results</th></tr>' . $s . '
			</table>
			</div>';
    }
예제 #19
0
 public function recipientRender($el)
 {
     return \Nette\Utils\Html::el("span")->addAttributes(["title" => $el->getRecipient()])->setText(\Nette\Utils\Strings::truncate($el->getRecipient(), 17));
 }
예제 #20
0
 /**
  * Returns syntax highlighted SQL command.
  * @param  string
  * @return string
  */
 public static function dumpSql($sql, array $params = NULL, Connection $connection = NULL)
 {
     static $keywords1 = 'SELECT|(?:ON\\s+DUPLICATE\\s+KEY)?UPDATE|INSERT(?:\\s+INTO)?|REPLACE(?:\\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|OFFSET|SET|VALUES|LEFT\\s+JOIN|INNER\\s+JOIN|TRUNCATE';
     static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|[RI]?LIKE|REGEXP|TRUE|FALSE';
     // insert new lines
     $sql = " {$sql} ";
     $sql = preg_replace("#(?<=[\\s,(])({$keywords1})(?=[\\s,)])#i", "\n\$1", $sql);
     // reduce spaces
     $sql = preg_replace('#[ \\t]{2,}#', ' ', $sql);
     $sql = wordwrap($sql, 100);
     $sql = preg_replace('#([ \\t]*\\r?\\n){2,}#', "\n", $sql);
     // syntax highlight
     $sql = htmlSpecialChars($sql, ENT_IGNORE, 'UTF-8');
     $sql = preg_replace_callback("#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])({$keywords1})(?=[\\s,)])|(?<=[\\s,(=])({$keywords2})(?=[\\s,)=])#is", function ($matches) {
         if (!empty($matches[1])) {
             // comment
             return '<em style="color:gray">' . $matches[1] . '</em>';
         } elseif (!empty($matches[2])) {
             // error
             return '<strong style="color:red">' . $matches[2] . '</strong>';
         } elseif (!empty($matches[3])) {
             // most important keywords
             return '<strong style="color:blue">' . $matches[3] . '</strong>';
         } elseif (!empty($matches[4])) {
             // other keywords
             return '<strong style="color:green">' . $matches[4] . '</strong>';
         }
     }, $sql);
     // parameters
     $sql = preg_replace_callback('#\\?#', function () use($params, $connection) {
         static $i = 0;
         if (!isset($params[$i])) {
             return '?';
         }
         $param = $params[$i++];
         if (is_string($param) && (preg_match('#[^\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}]#u', $param) || preg_last_error())) {
             return '<i title="Length ' . strlen($param) . ' bytes">&lt;binary&gt;</i>';
         } elseif (is_string($param)) {
             $length = Nette\Utils\Strings::length($param);
             $truncated = Nette\Utils\Strings::truncate($param, Helpers::$maxLength);
             $text = htmlspecialchars($connection ? $connection->quote($truncated) : '\'' . $truncated . '\'', ENT_NOQUOTES, 'UTF-8');
             return '<span title="Length ' . $length . ' characters">' . $text . '</span>';
         } elseif (is_resource($param)) {
             $type = get_resource_type($param);
             if ($type === 'stream') {
                 $info = stream_get_meta_data($param);
             }
             return '<i' . (isset($info['uri']) ? ' title="' . htmlspecialchars($info['uri'], ENT_NOQUOTES, 'UTF-8') . '"' : NULL) . '>&lt;' . htmlSpecialChars($type, ENT_NOQUOTES, 'UTF-8') . ' resource&gt;</i> ';
         } else {
             return htmlspecialchars($param, ENT_NOQUOTES, 'UTF-8');
         }
     }, $sql);
     return '<pre class="dump">' . trim($sql) . "</pre>\n";
 }
예제 #21
0
 private function error($message = "Unexpected '%s'")
 {
     list(, $line, $col) = self::$tokenizer->getOffset($this->n);
     $token = isset(self::$tokenizer->tokens[$this->n]) ? str_replace("\n", '<new line>', Strings::truncate(self::$tokenizer->tokens[$this->n], 40)) : 'end';
     throw new NeonException(str_replace('%s', $token, $message) . " on line {$line}, column {$col}.");
 }
예제 #22
0
파일: Neon.php 프로젝트: cujan/atlashornin
 private function error($message = "Unexpected '%s'")
 {
     $last = isset($this->tokens[$this->n]) ? $this->tokens[$this->n] : NULL;
     list($line, $col) = Tokenizer::getCoordinates($this->input, $last ? $last[Tokenizer::OFFSET] : strlen($this->input));
     $token = $last ? str_replace("\n", '<new line>', Strings::truncate($last[0], 40)) : 'end';
     throw new NeonException(str_replace('%s', $token, $message) . " on line {$line}, column {$col}.");
 }
예제 #23
0
 /**
  * @param array $row
  * @return string
  */
 public function prepareValue($row)
 {
     if (!empty($this->renderer)) {
         $value = call_user_func($this->renderer, (object) $row);
     } else {
         if (!empty($this->templateRenderer)) {
             $value = $this->renderTemplate((object) $row);
         } else {
             $value = $row[$this->name];
         }
     }
     if (!empty($this->truncate)) {
         $value = \Nette\Utils\Strings::truncate($value, $this->truncate);
     }
     return $this->escapingDisabled ? $value : htmlSpecialChars($value);
 }
예제 #24
0
파일: Column.php 프로젝트: natrim/gridito
 /**
  * Render email as list
  * @param $array
  * @param $maxlen
  * @return string
  */
 public function renderArray($array, $maxlen)
 {
     $text = implode($this->arrayDelimiter, (array) $array);
     if (is_null($maxlen) || Strings::length($text) < $maxlen) {
         return $text;
     } else {
         return Strings::truncate($text, $maxlen);
     }
 }
예제 #25
0
 /**
  * Import taken from Adminer, slightly modified
  * This implementation is aware of delimiters used for trigger definitions
  *
  * @author   Jakub Vrána, Jan Tvrdík, Michael Moravec, Filip Procházka
  * @license  Apache License
  */
 public static function executeBatch(Connection $connection, $query, $callback = NULL)
 {
     $db = $connection->getWrappedConnection();
     $delimiter = ';';
     $offset = 0;
     while ($query != '') {
         if (!$offset && preg_match('~^\\s*DELIMITER\\s+(.+)~i', $query, $match)) {
             $delimiter = $match[1];
             $query = substr($query, strlen($match[0]));
         } else {
             preg_match('(' . preg_quote($delimiter) . '|[\'`"]|/\\*|-- |#|$)', $query, $match, PREG_OFFSET_CAPTURE, $offset);
             // should always match
             $found = $match[0][0];
             $offset = $match[0][1] + strlen($found);
             if (!$found && rtrim($query) === '') {
                 break;
             }
             if (!$found || $found == $delimiter) {
                 // end of a query
                 $q = substr($query, 0, $match[0][1]);
                 try {
                     if ($callback) {
                         call_user_func($callback, $q, $db);
                     }
                     $db->query($q);
                 } catch (\Exception $e) {
                     throw new BatchImportException($e->getMessage() . "\n\n" . Nette\Utils\Strings::truncate(trim($q), 1200), 0, $e);
                 }
                 $query = substr($query, $offset);
                 $offset = 0;
             } else {
                 // find matching quote or comment end
                 while (preg_match('~' . ($found == '/*' ? '\\*/' : (preg_match('~-- |#~', $found) ? "\n" : "{$found}|\\\\.")) . '|$~s', $query, $match, PREG_OFFSET_CAPTURE, $offset)) {
                     //! respect sql_mode NO_BACKSLASH_ESCAPES
                     $s = $match[0][0];
                     $offset = $match[0][1] + strlen($s);
                     if ($s[0] !== '\\') {
                         break;
                     }
                 }
             }
         }
     }
 }
예제 #26
0
파일: TypeVote.php 프로젝트: krupaj/my-blog
 /**
  * @param int|NULL $length
  * @return string Napovedny text k vyplneni otazky
  */
 public function getDescription($length = NULL)
 {
     if ($length !== NULL) {
         return Strings::truncate($this->description, $length);
     }
     return $this->description;
 }
예제 #27
0
 /**
  * Digest helper
  *
  * @param $postContent
  * @param int $length
  * @return string
  */
 public function createPostDigestExcerpt($postContent, $length = 135)
 {
     $postContent = strip_tags(strip_shortcodes($postContent));
     $postContent = \Nette\Utils\Strings::fixEncoding($postContent);
     return \Nette\Utils\Strings::truncate($postContent, $length);
 }
예제 #28
0
 private function getMigrationFile($name, $postfix = NULL)
 {
     if ($postfix) {
         $postfix = '-' . Strings::webalize(Strings::truncate($postfix, 30));
     }
     return $this->getMigrationPath() . "/{$name}{$postfix}";
 }
예제 #29
0
 /**
  * Grid column render.
  * @param Article $e
  * @return string
  */
 public function titleRender($e)
 {
     return \Nette\Utils\Html::el("span")->addAttributes(["title" => $e->getTitle()])->setText(\Nette\Utils\Strings::truncate($e->getTitle(), 20));
 }
예제 #30
0
 /**
  * @param array $row
  * @return string
  */
 public function prepareValue($row)
 {
     if (!empty($this->renderer)) {
         $value = call_user_func($this->renderer, (object) $row);
     } else {
         $value = $row[$this->name];
     }
     if (!empty($this->truncate)) {
         return \Nette\Utils\Strings::truncate($value, $this->truncate);
     } else {
         return $value;
     }
 }