作者:leonardoc
项目:tool
/**
* Dump rendered Html element or code and intended output generated by tidy and optional also Html element structure
*
* @param Html|string $htmlElement Html element or string
* @param bool $onlyReturn output in string and don't send it to output?
* @param int $maxDepth for Debugger::Dump output - to see how is the Html element built
* @param bool $includePrettyPrint along javascript code for prettyPrint activation?
* @return string Html output
*/
function dumpHtml($htmlElement, $onlyReturn = false, $maxDepth = 0, $includePrettyPrint = false)
{
$maxDepthBackup = Debugger::$maxDepth;
$maxLenBackup = Debugger::$maxLen;
$showLocationBackup = Debugger::$showLocation;
Debugger::$maxDepth = $maxDepth;
Debugger::$maxLen = 200000;
Debugger::$showLocation = false;
// convert to string only once - important for Scaffolding Renderer output
$renderedElement = (string) $htmlElement;
$output = '<div class="rendered-element">' . $renderedElement . '</div>';
$output .= '<pre class="prettyprint linenums pre-scrollable">' . htmlspecialchars(tidyFormatString($renderedElement)) . '</pre>';
if ($includePrettyPrint) {
$output .= '<script>prettyPrint();</script>';
}
if ($maxDepth > 0 && $htmlElement instanceof \Latte\Runtime\Html) {
Debugger::dump($renderedElement);
Debugger::dump($htmlElement);
}
Debugger::$maxDepth = $maxDepthBackup;
Debugger::$maxLen = $maxLenBackup;
Debugger::$showLocation = $showLocationBackup;
if (!$onlyReturn) {
echo $output;
}
return $output;
}
作者:leonardoc
项目:tool
/**
* LeonardoCA\Tools\ProcessMonitor detail dump
*
* @param string $msg
* @param null $data
* @param null $dataDescription
* @param int $maxDepth
* @return void
*/
function pmd($msg = 'Detail Info', $data = null, $dataDescription = null, $maxDepth = 2)
{
$backupDepth = Debugger::$maxDepth;
Debugger::$maxDepth = $maxDepth;
ProcessMonitor::dump("<em style='color:#339'>{$msg}</em>", $data, null, ProcessMonitor::SHOW_DETAIL, $dataDescription);
Debugger::$maxDepth = $backupDepth;
}
作者:ondr
项目:nette-bootstra
/**
* Default form handler
*/
public function process()
{
/** @var ArrayHash $values */
$values = $this->values;
try {
$this->onBeforeProcess($this, $values);
if (isset($values->id)) {
$this->onBeforeUpdate($this, $values);
$arr = (array) $values;
unset($arr['id']);
$row = $this->selection->wherePrimary($values->id)->fetch();
$row->update($arr);
$this->onAfterUpdate($row, $this, $values);
} else {
$this->onBeforeInsert($this, $values);
$row = $this->selection->insert($values);
$this->onAfterInsert($row, $this, $values);
}
$this->onAfterProcess($row, $this, $values);
} catch (\PDOException $e) {
$this->addError($e->getMessage());
dump($e);
Debugger::log($e);
}
}
作者:regis
项目:doctrine-san
public function renderDefault()
{
$this->template->anyVariable = 'any value';
// $dao = $this->articles;
$this->template->articles = $this->articles->getArticles()->findAll();
$posts = $this->EntityManager->getRepository(Posts::getClassName());
$this->template->posts = $posts->findAll();
$this->template->myparametr = $this->context->parameters['first_parametr'];
// $this->template->test = $this->doSomeRefactoring('Hello world from blog');
// $post = new Posts();
// $post->title = 'New title';
// $post->text = 'New text New textNew text';
// $post->created_at = new \Nette\Utils\DateTime;
//
//
// $this->EntityManager->persist($post);
// $this->EntityManager->flush();
// $dao = $this->EntityManager->getRepository(Posts::getClassName());
// $dao->setTitle('test');
// $dao->__call('set', ['title' => 'my title']);
// dump($dao->__isset('title'));
// $dao->__set('title', 'test');
try {
$this->checkNum(2);
\Tracy\Debugger::barDump('If you see this, the number is 1 or below');
} catch (Nette\Application\BadRequestException $e) {
Debugger::log('Message: ' . $e->getMessage());
var_dump($e->getMessage());
}
// finally {
// \Tracy\Debugger::barDump('Got here Finally');
// }
}
作者:block
项目:php2j
protected function execute(InputInterface $input, OutputInterface $output)
{
Debugger::timer();
$output->writeln('Running tests...');
$runner = new Runner();
$path = realpath($input->getArgument('path'));
if ($path) {
if (is_dir($path)) {
$runner->setTestsRoot($path . '/');
foreach (Finder::findFiles('*.php')->exclude('tester.php')->from($path) as $path => $fileInfo) {
$basePath = Helpers::stripExtension($path);
$runner->addTest($basePath);
}
} else {
$basePath = Helpers::stripExtension($path);
$runner->addTest($basePath);
}
} else {
if ($path = realpath($input->getArgument('path') . '.php')) {
$basePath = Helpers::stripExtension($path);
$runner->addTest($basePath);
} else {
$output->writeln("<error>The given path isn't valid</error>");
return 1;
}
}
$runner->setOutput($output);
$runner->runTests();
$output->writeln('Completed in ' . round(Debugger::timer(), 2) . ' seconds');
if ($runner->failed()) {
return 1;
} else {
return 0;
}
}
作者:jiang5
项目:mond
public function __init($directory = NULL, $email = NULL, BlueScreen $blueScreen = NULL)
{
if (!$directory) {
$directory = __DIR__ . "/../log/";
}
if (getenv("MONDA_DEBUG")) {
if (array_key_exists(getenv("MONDA_DEBUG"), self::$levels)) {
self::$loglevel = self::$levels[getenv("MONDA_DEBUG")];
Debugger::$productionMode = false;
} else {
self::log("Unknown log level!\n", Debugger::ERROR);
}
} else {
if (Options::get("debug")) {
if (array_key_exists(Options::get("debug"), self::$levels)) {
self::$loglevel = self::$levels[Options::get("debug")];
Debugger::$productionMode = false;
} else {
self::log("Unknown log level!\n", Debugger::ERROR);
}
}
}
self::$wwwlogger = new \Tracy\Logger($directory, $email, $blueScreen);
if (PHP_SAPI == "cli") {
if (Options::get("logfile")) {
self::$logfd = fopen(Options::get("logfile"), "w");
} else {
self::$logfd = STDERR;
}
}
}
作者:gorocache
项目:react-http-server-sandbo
private function handleRequest(React\Http\Request $request, React\Http\Response $response)
{
try {
$container = $this->containerFactory->createContainer();
/** @var HttpRequestFactory $requestFactory */
$requestFactory = $container->getByType(HttpRequestFactory::class);
$requestFactory->setFakeHttpRequest($this->createNetteHttpRequest($request));
/** @var CliRouter $router */
$cliRouter = $container->getService('console.router');
$cliRouter->setIsCli(FALSE);
/** @var Nette\Application\Application $application */
$application = $container->getByType(Nette\Application\Application::class);
array_unshift($application->onError, function () {
throw new AbortException();
});
ob_start();
$application->run();
$responseBody = ob_get_contents();
ob_end_clean();
$response->writeHead(200, array('Content-Type' => 'text/html; charset=utf-8'));
$response->end($responseBody);
} catch (\Exception $e) {
Debugger::log($e, Debugger::EXCEPTION);
$response->writeHead(500, array('Content-Type' => 'text/plain'));
$response->end('Internal Server Error');
}
}
作者:kebool
项目:php-db-impor
protected function importDataToStagingTable($stagingTableName, $columns, $sourceData)
{
if (!isset($sourceData['schemaName'])) {
throw new Exception('Invalid source data. schemaName must be set', Exception::INVALID_SOURCE_DATA);
}
if (!isset($sourceData['tableName'])) {
throw new Exception('Invalid source data. schemaName must be set', Exception::INVALID_SOURCE_DATA);
}
$sql = "INSERT INTO " . $this->nameWithSchemaEscaped($stagingTableName) . " (" . implode(', ', array_map(function ($column) {
return $this->quoteIdentifier($column);
}, $columns)) . ") ";
$sql .= "SELECT " . implode(',', array_map(function ($column) {
return $this->quoteIdentifier($column);
}, $columns)) . " FROM " . $this->nameWithSchemaEscaped($sourceData['tableName'], $sourceData['schemaName']);
try {
Debugger::timer('copyToStaging');
$this->connection->query($sql);
$rows = $this->connection->fetchAll(sprintf('SELECT COUNT(*) as "count" from %s.%s', $this->connection->quoteIdentifier($this->schemaName), $this->connection->quoteIdentifier($stagingTableName)));
$this->importedRowsCount += (int) $rows[0]['count'];
$this->addTimer('copyToStaging', Debugger::timer('copyToStaging'));
} catch (\Exception $e) {
// everything is user error
throw new Exception($e->getMessage(), Exception::UNKNOWN_ERROR, $e);
}
}
作者:MatyC
项目:LemoTrac
/**
* {@inheritDoc}
*/
public function onBootstrap(EventInterface $event)
{
/**
* @var ModuleOptions $moduleOptions
*/
$moduleOptions = $event->getTarget()->getServiceManager()->get('LemoTracy\\Options\\ModuleOptions');
if (true === $moduleOptions->getEnabled()) {
if (null !== $moduleOptions->getMode()) {
Debugger::enable($moduleOptions->getMode());
}
if (null !== $moduleOptions->getLogDirectory()) {
Debugger::$logDirectory = $moduleOptions->getLogDirectory();
}
if (null !== $moduleOptions->getLogSeverity()) {
Debugger::$logSeverity = $moduleOptions->getLogSeverity();
}
if (null !== $moduleOptions->getMaxDepth()) {
Debugger::$maxDepth = $moduleOptions->getMaxDepth();
}
if (null !== $moduleOptions->getMaxLen()) {
Debugger::$maxLen = $moduleOptions->getMaxLen();
}
if (null !== $moduleOptions->getShowBar()) {
Debugger::$showBar = $moduleOptions->getShowBar();
}
if (null !== $moduleOptions->getStrict()) {
Debugger::$strictMode = $moduleOptions->getStrict();
}
}
}
作者:kebool
项目:php-db-impor
protected function importDataToStagingTable($stagingTempTableName, $columns, $sourceData, array $options = [])
{
if (!isset($sourceData['schemaName'])) {
throw new Exception('Invalid source data. schemaName must be set', Exception::INVALID_SOURCE_DATA);
}
if (!isset($sourceData['tableName'])) {
throw new Exception('Invalid source data. schemaName must be set', Exception::INVALID_SOURCE_DATA);
}
$sourceColumnTypes = $this->describeTable(strtolower($sourceData['tableName']), strtolower($sourceData['schemaName']));
$sql = "INSERT INTO " . $this->tableNameEscaped($stagingTempTableName) . " (" . implode(', ', array_map(function ($column) {
return $this->quoteIdentifier($column);
}, $columns)) . ") ";
$sql .= "SELECT " . implode(',', array_map(function ($column) use($sourceColumnTypes) {
if ($sourceColumnTypes[$column]['DATA_TYPE'] === 'bool') {
return sprintf('DECODE(%s, true, 1, 0) ', $this->quoteIdentifier($column));
} else {
return "COALESCE(CAST({$this->quoteIdentifier($column)} as varchar), '') ";
}
}, $columns)) . " FROM " . $this->nameWithSchemaEscaped($sourceData['tableName'], $sourceData['schemaName']);
try {
Debugger::timer('copyToStaging');
$this->query($sql);
$this->addTimer('copyToStaging', Debugger::timer('copyToStaging'));
} catch (\Exception $e) {
if (strpos($e->getMessage(), 'Datatype mismatch') !== false) {
throw new Exception($e->getMessage(), Exception::DATA_TYPE_MISMATCH, $e);
}
// everything is user error
throw new Exception($e->getMessage(), Exception::UNKNOWN_ERROR, $e);
}
}
作者:martinmaye
项目:noteja
/**
* Callback for ForgottenPasswordForm onSuccess event.
* @param Form $form
* @param ArrayHash $values
*/
public function formSucceeded(Form $form, $values)
{
$user = $this->userManager->findByEmail($values->email);
if (!$user) {
$form->addError('No user with given email found');
return;
}
$password = Nette\Utils\Random::generate(10);
$this->userManager->setNewPassword($user->id, $password);
try {
// !!! Never send passwords through email !!!
// This is only for demonstration purposes of Notejam.
// Ideally, you can create a unique link where user can change his password
// himself for limited amount of time, and then send the link.
$mail = new Nette\Mail\Message();
$mail->setFrom('noreply@notejamapp.com', 'Notejamapp');
$mail->addTo($user->email);
$mail->setSubject('New notejam password');
$mail->setBody(sprintf('Your new password: %s', $password));
$this->mailer->send($mail);
} catch (Nette\Mail\SendException $e) {
Debugger::log($e, Debugger::EXCEPTION);
$form->addError('Could not send email with new password');
}
}
作者:foowi
项目:cro
public static function register(Cron $cron, Request $request)
{
$bar = Debugger::getBar();
$panel = new static($cron, $request);
$bar->addPanel($panel);
return $panel;
}
作者:maty
项目:guzzlett
/**
* @param $tempDir
* @param array $guzzleConfig
* @return \GuzzleHttp\Client
* @throws \Matyx\Guzzlette\GuzzletteException
*/
public static function createGuzzleClient($tempDir, $guzzleConfig = [])
{
if (isset(static::$client)) {
return static::$client;
}
if (Tracy\Debugger::isEnabled()) {
$handler = NULL;
if (isset($guzzleConfig['handler'])) {
$handler = $guzzleConfig['handler'];
if (!$handler instanceof GuzzleHttp\HandlerStack) {
throw new GuzzletteException("Handler must be instance of " . GuzzleHttp\HandlerStack::class);
}
} else {
$handler = GuzzleHttp\HandlerStack::create();
}
$requestStack = new RequestStack();
Tracy\Debugger::getBar()->addPanel(new TracyPanel($tempDir, $requestStack));
$handler->push(function (callable $handler) use($requestStack) {
return function ($request, array $options) use($handler, $requestStack) {
Tracy\Debugger::timer();
$guzzletteRequest = new Request();
$guzzletteRequest->request = $request;
return $handler($request, $options)->then(function ($response) use($requestStack, $guzzletteRequest) {
$guzzletteRequest->time = Tracy\Debugger::timer();
$guzzletteRequest->response = $response;
$requestStack->addRequest($guzzletteRequest);
return $response;
});
};
});
$guzzleConfig['handler'] = $handler;
}
static::$client = new GuzzleHttp\Client($guzzleConfig);
return static::$client;
}
作者:ricco2
项目:gitlab-auto-merge
/**
* Provide auto merge
*/
public function actionDefault()
{
$payload = $this->httpRequest->getRawBody();
if (!$payload) {
Debugger::log('No payload data', Debugger::ERROR);
$this->terminate();
}
$data = json_decode($payload, true);
if (!$data) {
Debugger::log('json_decode error', Debugger::ERROR);
$this->terminate();
}
if ($data['object_kind'] != 'note') {
Debugger::log('Only notes object kind processing now. *' . $data['object_kind'] . '* given', Debugger::ERROR);
$this->terminate();
}
$projectId = isset($data['merge_request']['source_project_id']) ? $data['merge_request']['source_project_id'] : false;
$mergeRequestId = isset($data['merge_request']['id']) ? $data['merge_request']['id'] : false;
if (!$projectId || !$mergeRequestId) {
Debugger::log('projectId or mergeRequestId missing', Debugger::ERROR);
$this->terminate();
}
$project = $this->projectRepository->findByGitlabId($projectId);
if (!$project) {
Debugger::log('Project ' . $projectId . ' is not allowed to auto merge', Debugger::ERROR);
$this->terminate();
}
$mr = $this->gitlabClient->api('mr')->show($projectId, $mergeRequestId);
$mergeRequest = $this->mergeRequestBuilder->create($mr, $data);
if ($mergeRequest->canBeAutoMerged($project->positive_votes)) {
$this->gitlabClient->api('mr')->merge($projectId, $mergeRequestId, 'Auto merged');
}
}
作者:green
项目:nette-slack-logge
public function __construct($slackUrl, IMessageFactory $messageFactory, $timeout)
{
parent::__construct(Debugger::$logDirectory, Debugger::$email, Debugger::getBlueScreen());
$this->slackUrl = $slackUrl;
$this->messageFactory = $messageFactory;
$this->timeout = $timeout;
}
作者:Kaspis7
项目:Faceboo
/**
* Parses a signed_request and validates the signature.
*
* @param string $signedRequest A signed token
* @param string $appSecret
*
* @return array The payload inside it or null if the sig is wrong
*/
public static function decode($signedRequest, $appSecret)
{
if (!$signedRequest || strpos($signedRequest, '.') === false) {
Debugger::log('Signed request is invalid! ' . json_encode($signedRequest), 'facebook');
return NULL;
}
list($encoded_sig, $payload) = explode('.', $signedRequest, 2);
// decode the data
$sig = Helpers::base64UrlDecode($encoded_sig);
$data = Json::decode(Helpers::base64UrlDecode($payload), Json::FORCE_ARRAY);
if (!isset($data['algorithm']) || strtoupper($data['algorithm']) !== Configuration::SIGNED_REQUEST_ALGORITHM) {
Debugger::log("Unknown algorithm '{$data['algorithm']}', expected " . Configuration::SIGNED_REQUEST_ALGORITHM, 'facebook');
return NULL;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $appSecret, $raw = TRUE);
if (strlen($expected_sig) !== strlen($sig)) {
Debugger::log('Bad Signed JSON signature! Expected ' . Dumper::toText($expected_sig) . ', but given ' . Dumper::toText($sig), 'facebook');
return NULL;
}
$result = 0;
for ($i = 0; $i < strlen($expected_sig); $i++) {
$result |= ord($expected_sig[$i]) ^ ord($sig[$i]);
}
if ($result !== 0) {
Debugger::log('Bad Signed JSON signature! Expected ' . Dumper::toText($expected_sig) . ', but given ' . Dumper::toText($sig), 'facebook');
return NULL;
}
return $data;
}
作者:kiz
项目:easyminer-easyminercente
/**
* Funkce pro odeslání GET požadavku bez čekání na získání odpovědi
* @param string $url
* @throws \Exception
*/
public static function sendBackgroundGetRequest($url)
{
$url = new Url($url);
$host = $url->getHost();
if (empty($host)) {
$host = 'localhost';
}
#region parametry připojení
switch ($url->getScheme()) {
case 'https':
$scheme = 'ssl://';
$port = 443;
break;
case 'http':
default:
$scheme = '';
$port = 80;
}
$urlPort = $url->getPort();
if (!empty($urlPort)) {
$port = $urlPort;
}
#endregion
$fp = @fsockopen($scheme . $host, $port, $errno, $errstr, self::REQUEST_TIMEOUT);
if (!$fp) {
Debugger::log($errstr, ILogger::ERROR);
throw new \Exception($errstr, $errno);
}
$path = $url->getPath() . ($url->getQuery() != "" ? '?' . $url->getQuery() : '');
fputs($fp, "GET " . $path . " HTTP/1.0\r\nHost: " . $host . "\r\n\r\n");
fputs($fp, "Connection: close\r\n");
fputs($fp, "\r\n");
}
作者:YepFoundatio
项目:tracy-twig-extension
protected function doDump($data)
{
if (!class_exists('\\Tracy\\Debugger')) {
return;
}
Debugger::barDump($data, null, $this->options);
}
作者:kebool
项目:php-db-impor
/**
* @param $tempTableName
* @param $columns
* @param CsvFile $csvFile
* @param array $options
* - isManifest
* - copyOptions
* @throws Exception
* @throws \Exception
*/
protected function importTable($tempTableName, $columns, CsvFile $csvFile, array $options)
{
if ($csvFile->getEnclosure() && $csvFile->getEscapedBy()) {
throw new Exception('Invalid CSV params. Either enclosure or escapedBy must be specified for Redshift backend but not both.', Exception::INVALID_CSV_PARAMS, null);
}
try {
Debugger::timer('copyToStaging');
$copyOptions = ['isManifest' => $options['isManifest'], 'copyOptions' => isset($options['copyOptions']) ? $options['copyOptions'] : []];
if ($options['isManifest']) {
$manifest = $this->downloadManifest($csvFile->getPathname());
// empty manifest handling - do nothing
if (!count($manifest['entries'])) {
$this->addTimer('copyToStaging', Debugger::timer('copyToStaging'));
return;
}
$copyOptions['isGzipped'] = $this->isGzipped(reset($manifest['entries'])['url']);
} else {
$copyOptions['isGzipped'] = $this->isGzipped($csvFile->getPathname());
}
$this->query($this->generateCopyCommand($tempTableName, $columns, $csvFile, $copyOptions));
$this->addTimer('copyToStaging', Debugger::timer('copyToStaging'));
} catch (\Exception $e) {
$result = $this->connection->query("SELECT * FROM stl_load_errors WHERE query = pg_last_query_id();")->fetchAll();
if (!count($result)) {
throw $e;
}
$messages = [];
foreach ($result as $row) {
$messages[] = "Line {$row['line_number']} - {$row['err_reason']}";
}
$message = "Load error: " . implode("\n", $messages);
throw new Exception($message, Exception::INVALID_SOURCE_DATA, $e);
}
}
作者:petrparole
项目:web_cm
public static function initialize()
{
$blueScreen = Tracy\Debugger::getBlueScreen();
if (preg_match('#(.+)/Bridges/Framework$#', strtr(__DIR__, '\\', '/'), $m)) {
if (preg_match('#(.+)/nette/bootstrap/src$#', $m[1], $m2)) {
$blueScreen->collapsePaths[] = "{$m2['1']}/nette";
$blueScreen->collapsePaths[] = "{$m2['1']}/latte";
} else {
$blueScreen->collapsePaths[] = $m[1];
}
}
if (class_exists('Nette\\Framework')) {
$bar = Tracy\Debugger::getBar();
$bar->info[] = $blueScreen->info[] = 'Nette Framework ' . Nette\Framework::VERSION . ' (' . Nette\Framework::REVISION . ')';
}
$blueScreen->addPanel(function ($e) {
if ($e instanceof Latte\CompileException) {
return array('tab' => 'Template', 'panel' => '<p>' . (is_file($e->sourceName) ? '<b>File:</b> ' . Helpers::editorLink($e->sourceName, $e->sourceLine) : htmlspecialchars($e->sourceName)) . '</p>' . ($e->sourceCode ? '<pre>' . BlueScreen::highlightLine(htmlspecialchars($e->sourceCode), $e->sourceLine) . '</pre>' : ''));
} elseif ($e instanceof Nette\Neon\Exception && preg_match('#line (\\d+)#', $e->getMessage(), $m)) {
if ($item = Helpers::findTrace($e->getTrace(), 'Nette\\DI\\Config\\Adapters\\NeonAdapter::load')) {
return array('tab' => 'NEON', 'panel' => '<p><b>File:</b> ' . Helpers::editorLink($item['args'][0], $m[1]) . '</p>' . BlueScreen::highlightFile($item['args'][0], $m[1]));
} elseif ($item = Helpers::findTrace($e->getTrace(), 'Nette\\Neon\\Decoder::decode')) {
return array('tab' => 'NEON', 'panel' => BlueScreen::highlightPhp($item['args'][0], $m[1]));
}
}
});
}