예제 #1
0
/**
 * 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;
}
예제 #2
0
/**
 * 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;
}
예제 #3
0
 /**
  * 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);
     }
 }
예제 #4
0
 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');
     //		}
 }
예제 #5
0
 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;
     }
 }
예제 #6
0
파일: CliLogger.php 프로젝트: jiang51/monda
 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;
         }
     }
 }
 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');
     }
 }
예제 #8
0
 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);
     }
 }
예제 #9
0
파일: Module.php 프로젝트: MatyCZ/LemoTracy
 /**
  * {@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();
         }
     }
 }
예제 #10
0
 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);
     }
 }
 /**
  * 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('*****@*****.**', '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');
     }
 }
예제 #12
0
파일: Panel.php 프로젝트: foowie/cron
 public static function register(Cron $cron, Request $request)
 {
     $bar = Debugger::getBar();
     $panel = new static($cron, $request);
     $bar->addPanel($panel);
     return $panel;
 }
예제 #13
0
 /**
  * @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;
 }
 /**
  * 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');
     }
 }
예제 #15
0
 public function __construct($slackUrl, IMessageFactory $messageFactory, $timeout)
 {
     parent::__construct(Debugger::$logDirectory, Debugger::$email, Debugger::getBlueScreen());
     $this->slackUrl = $slackUrl;
     $this->messageFactory = $messageFactory;
     $this->timeout = $timeout;
 }
예제 #16
0
 /**
  * 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;
 }
 /**
  * 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");
 }
 protected function doDump($data)
 {
     if (!class_exists('\\Tracy\\Debugger')) {
         return;
     }
     Debugger::barDump($data, null, $this->options);
 }
예제 #19
0
 /**
  * @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);
     }
 }
예제 #20
0
 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]));
             }
         }
     });
 }
예제 #21
0
 /**
  * Register the bar and register the event which will block the screen log
  */
 public static function register()
 {
     $class = new self();
     Events::addListener(array($class, 'screenLogEventListener'), 'screenLogEvent', EventPriority::NORMAL);
     $bar = Debugger::getBar();
     $bar->addPanel($class);
 }
예제 #22
0
 public function register(ORM &$db)
 {
     Debugger::getBar()->addPanel($this);
     $db->debug = function ($query, $parameters, $microtime = null) {
         self::getInstance()->logQuery($query, $parameters, $microtime);
     };
 }
예제 #23
0
파일: shortcuts.php 프로젝트: aprila/utils
 /**
  * Shortcut for Debugger::dump & exit()
  *
  * @author   Jan Tvrdík
  * @param    mixed
  * @param    mixed $var , ... optional additional variable(s) to dump
  * @return   void
  */
 function de($var)
 {
     foreach (func_get_args() as $var) {
         Debugger::dump($var);
     }
     exit;
 }
예제 #24
0
 /**
  * Nette render default method
  *
  * @return void
  */
 public function renderDefault()
 {
     $start = microtime(true);
     $this->sendCorsHeaders();
     $hand = $this->getHandler();
     $handler = $hand['handler'];
     $authorization = $hand['authorization'];
     if ($this->checkAuth($authorization) === false) {
         return;
     }
     $params = $this->processParams($handler);
     if ($params === false) {
         return;
     }
     try {
         $response = $handler->handle($params);
         $code = $response->getCode();
     } catch (Exception $exception) {
         $response = new JsonApiResponse(500, ['status' => 'error', 'message' => 'Internal server error']);
         $code = $response->getCode();
         Debugger::log($exception, Debugger::EXCEPTION);
     }
     $end = microtime(true);
     if ($this->context->findByType('Tomaj\\NetteApi\\Logger\\ApiLoggerInterface')) {
         $this->logRequest($this->context->getByType('Tomaj\\NetteApi\\Logger\\ApiLoggerInterface'), $code, $end - $start);
     }
     // output to nette
     $this->getHttpResponse()->setCode($code);
     $this->sendResponse($response);
 }
예제 #25
0
/**
 * Bar dump; die;
 */
function bdd()
{
    foreach (func_get_args() as $var) {
        Debugger::barDump($var);
    }
    die;
}
 /**
  * @param  Exception
  * @return void
  * @throws Nette\Application\AbortException
  */
 public function actionDefault($exception)
 {
     if ($exception instanceof Nette\Application\BadRequestException) {
         $code = $exception->getCode();
         // load template 403.latte or 404.latte or ... 4xx.latte
         $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         if (Debugger::isEnabled()) {
             // log to access.log
             Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
         }
     } else {
         $this->setView('500');
         // load template 500.latte
         if (Debugger::isEnabled()) {
             Debugger::log($exception, Debugger::ERROR);
             // and log exception
         }
     }
     $this->template->exception = $exception;
     if ($this->isAjax()) {
         // AJAX request? Note this error in payload.
         $this->payload->error = true;
         $this->terminate();
     }
 }
예제 #27
0
 public function startup()
 {
     parent::startup();
     \Tracy\Debugger::timer('global');
     // Log visits
     // todo: replace by mongoDB log_visit
     /*
     
     		$httpRequest = $this->getHttpRequest();
     		$requestHeaders = apache_request_headers();
     		$ipAddress = (empty($requestHeaders['X-Forwarded-For']) ? $httpRequest->getRemoteAddress() : $requestHeaders['X-Forwarded-For']);
     		// ip address can be more values divided by comma (it's path to remote server), take only the last (most accurate IP of visitor)
     		$ipAddressParts = explode(',', $ipAddress);
     		$ipAddress = array_pop($ipAddressParts);
     		if ($httpRequest->getUrl()->path != '/healthy-check') {
     
     
     			$this->lastLogItem = $this->logger->logVisit(
     				$httpRequest->getUrl()->path, // URL
     				$ipAddress,  // IP
     				$httpRequest->getHeader('User-Agent'),  // USER_AGENT
     				$httpRequest->getReferer()  // REFERRER
     			);
     		}*/
 }
예제 #28
0
 /**
  * @param WorkedHours $workedHours
  * @return WorkedHours
  * @throws \DibiException
  */
 public function setupWorkedHours(WorkedHours $workedHours)
 {
     $values = ['workStart' => $workedHours->workStart->getTime(), 'workEnd' => $workedHours->workEnd->getTime(), 'lunch' => $workedHours->lunch->getTime(), 'otherHours' => $workedHours->otherHours->getTime()];
     try {
         $this->connection->query('LOCK TABLES worked_hours WRITE');
         $data = $this->connection->query('SELECT workedHoursID AS id FROM worked_hours
              WHERE %and', $values)->fetch();
         if ($data === false) {
             $this->connection->query('INSERT INTO [worked_hours]', $values);
             $id = $this->connection->getInsertId();
         } else {
             $id = $data['id'];
         }
         $this->connection->query('UNLOCK TABLES');
         if (!$workedHours->isDetached()) {
             $workedHours->detach();
         }
         $workedHours->makeAlive($this->entityFactory, $this->connection, $this->mapper);
         $workedHours->attach($id);
         return $workedHours;
     } catch (\DibiException $e) {
         $this->connection->query('UNLOCK TABLES');
         Debugger::log($e, Debugger::ERROR);
         throw $e;
     }
 }
예제 #29
0
 public function logQuery(Nette\Database\Connection $connection, $result)
 {
     if ($this->disabled) {
         return;
     }
     $this->count++;
     $source = NULL;
     $trace = $result instanceof \PDOException ? $result->getTrace() : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
     foreach ($trace as $row) {
         if (isset($row['file']) && is_file($row['file']) && !Tracy\Debugger::getBluescreen()->isCollapsed($row['file'])) {
             if (isset($row['function']) && strpos($row['function'], 'call_user_func') === 0 || isset($row['class']) && is_subclass_of($row['class'], '\\Nette\\Database\\Connection')) {
                 continue;
             }
             $source = [$row['file'], (int) $row['line']];
             break;
         }
     }
     if ($result instanceof Nette\Database\ResultSet) {
         $this->totalTime += $result->getTime();
         if ($this->count < $this->maxQueries) {
             $this->queries[] = [$connection, $result->getQueryString(), $result->getParameters(), $source, $result->getTime(), $result->getRowCount(), NULL];
         }
     } elseif ($result instanceof \PDOException && $this->count < $this->maxQueries) {
         $this->queries[] = [$connection, $result->queryString, NULL, $source, NULL, NULL, $result->getMessage()];
     }
 }
예제 #30
0
 /**
  * @param array $configs
  * @return Nette\DI\Container
  */
 protected function createContainer(array $configs = [])
 {
     $sl = $this->parentCreateContainer($configs);
     /** @var DbConnectionMock $db */
     $db = $sl->getByType('Doctrine\\DBAL\\Connection');
     if (!$db instanceof DbConnectionMock) {
         $serviceNames = $sl->findByType('Doctrine\\DBAL\\Connection');
         throw new \LogicException(sprintf('The service %s should be instance of Kdyby\\TesterExtras\\DbConnectionMock, to allow lazy schema initialization', reset($serviceNames)));
     }
     $db->onConnect[] = function (Connection $db) use($sl) {
         if ($this->databaseName !== NULL) {
             return;
         }
         try {
             if (!method_exists($this, 'doSetupDatabase')) {
                 throw new \LogicException(sprintf("Method %s:%s is not implemented", get_class($this), __FUNCTION__));
             }
             $this->doSetupDatabase($db);
         } catch (\Exception $e) {
             Tracy\Debugger::log($e, Tracy\Debugger::ERROR);
             Assert::fail($e->getMessage());
         }
     };
     return $sl;
 }