protected function _outputMessage($template) { $error = $this->controller->viewVars['error']; $data = []; $data['class'] = 'Error'; $data['code'] = $error->getCode(); $data['url'] = '/' . $this->controller->request->url; $data['message'] = $error->getMessage(); $data['errors'] = $this->controller->viewVars['errors']; if (Configure::read('debug')) { $data['DEBUG']['trace'] = Debugger::formatTrace($error->getTrace(), ['format' => 'array', 'args' => false]); $queryLog = $this->_getQueryLog(); if ($queryLog) { $data['DEBUG']['queryLog'] = $queryLog; } } $jsonOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT; if (Configure::read('debug')) { $jsonOptions = $jsonOptions | JSON_PRETTY_PRINT; } $this->controller->response->type('json'); $this->controller->response->body(json_encode($data, $jsonOptions)); $this->controller->response->statusCode($data['code']); return $this->controller->response; }
/** * {@inheritDoc} */ public function __construct(array $config = []) { if (Configure::read('debug')) { Debugger::checkSecurityKeys(); } parent::config($config); }
public function _createStreamDataWithEntity($entity, $entity_type) { // if(!$entity_type){ // $entity_type = get_class($entity); // } $entity_type_p = $entity_type . 's'; // debug($entity); // $game = $this->_contains($game)->first(); $success = $entity->format(null, 'feed_push'); if (!$success) { Debugger::log('It failed after formatting the game'); return false; } $base_data = ["object" => $entity_type . ":" . $entity->id, 'type' => "feed-" . strtolower($entity_type_p), 'foreign_id' => $entity_type . ":" . $entity->id, 'display' => $entity->display]; if ($entity_type == 'Game') { $specific_data = ["verb" => strtolower($entity->game_type_name), 'first_user_image' => $entity->winner_image, 'first_user_id' => $entity->winner_id, 'first_user_score' => $entity->winner_points, 'second_user_image' => $entity->loser_image, 'second_user_id' => $entity->loser_id, 'second_user_score' => $entity->loser_points, 'game_type_name' => $entity->game_type_name, 'time' => $entity->created]; } else { if ($entity_type == 'Friendship') { $specific_data = ["verb" => "friend", 'first_user_id' => $entity->first_user_id, 'first_user_image' => $entity->first_user_image, 'second_user_id' => $entity->second_user_id, 'second_user_image' => $entity->second_user_image, 'time' => $entity->modified]; } else { return false; } } $base_data = array_merge($base_data, $specific_data); return $base_data; }
/** * Start an benchmarking timer. * * @param string $name The name of the timer to start. * @param string $message A message for your timer * @return boolean Always true */ public static function start($name = null, $message = null) { $start = microtime(true); if (!$name) { $named = false; $calledFrom = debug_backtrace(); $_name = $name = Debugger::trimpath($calledFrom[0]['file']) . ' line ' . $calledFrom[0]['line']; } else { $named = true; } if (!$message) { $message = $name; } $_name = $name; $i = 1; while (isset(self::$_timers[$name])) { $i++; $name = $_name . ' #' . $i; } if ($i > 1) { $message .= ' #' . $i; } self::$_timers[$name] = array('start' => $start, 'message' => $message, 'named' => $named); return true; }
/** * Add a HTTP call to the data * * @param Request $request Call request * @param Response $response Call response * @param float $time duration of the call */ public static function addCall($request, $response, $time = null) { $calls = static::config('calls'); $trace = Debugger::trace(['start' => 2]); $calls[] = ['request' => ['uri' => (string) $request->getUri(), 'body' => $request->body(), 'method' => $request->getMethod(), 'headers' => $request->getHeaders(), 'content-type' => $request->getHeader('Content-Type')], 'response' => ['body' => $response->body(), 'status_code' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'content-type' => $response->getHeader('Content-Type')], 'time' => $time, 'trace' => $trace]; static::drop('calls'); static::config('calls', $calls); }
/** * get the body for htmll message * * @access private * @author sakuragawa */ private function getHtml($message, $file, $line, $context = null) { $params = Router::getRequest(); $trace = Debugger::trace(array('start' => 2, 'format' => 'base')); $session = isset($_SESSION) ? $_SESSION : array(); $msg = array('<p><strong>', $message, '</strong></p>', '<p>', $file . '(' . $line . ')', '</p>', '', '<h2>', 'Backtrace:', '</h2>', '', '<pre>', self::dumper($trace), '</pre>', '', '<h2>', 'Request:', '</h2>', '', '<h3>URL</h3>', $this->url(), '<h3>Client IP</h3>', $this->getClientIp(), '<h3>Referer</h3>', env('HTTP_REFERER'), '<h3>Parameters</h3>', self::dumper($params), '<h3>Cake root</h3>', APP, '', '<h2>', 'Environment:', '</h2>', '', self::dumper($_SERVER), '', '<h2>', 'Session:', '</h2>', '', self::dumper($session), '', '<h2>', 'Cookie:', '</h2>', '', self::dumper($_COOKIE), '', '<h2>', 'Context:', '</h2>', '', self::dumper($context), ''); return join("", $msg); }
/** * Add a HTTP call to the data * * @param $request * @param $response * @param $time */ public static function addCall($request, $response, $time = null) { $calls = static::config('calls'); $trace = Debugger::trace(['start' => 2]); $calls[] = ['request' => $request, 'response' => $response, 'time' => $time, 'trace' => $trace]; static::drop('calls'); static::config('calls', $calls); }
/** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class * * @return void */ public function change() { $table = $this->table('queued_tasks'); try { $adapter = new MysqlAdapter([]); if ($adapter->getSqlType('text', 'longtext')) { $table->changeColumn('data', 'text', ['limit' => MysqlAdapter::TEXT_LONG, 'null' => true, 'default' => null]); } } catch (Exception $e) { Debugger::dump($e->getMessage()); } }
/** * @param string $userId * @return bool */ public function createAdmin($userId) { $teamMembership = TableRegistry::get('TeamMemberships'); $adminship = new TeamMembership(['role' => 'admin', 'team_id' => $this->id, 'member_id' => $userId]); $isCurrentMember = $teamMembership->find()->where(['member_id' => $userId, 'team_id' => $this->id])->first(); Debugger::log($isCurrentMember); if (!empty($isCurrentMember)) { $adminship->id = $isCurrentMember->id; } if (!$teamMembership->save($adminship)) { return false; } return true; }
/** * Helper method used to generate extra debugging data into the error template * * @return array debugging data */ protected function _getErrorData() { $data = []; $viewVars = $this->controller->viewVars; if (!empty($viewVars['_serialize'])) { foreach ($viewVars['_serialize'] as $v) { $data[$v] = $viewVars[$v]; } } if (!empty($viewVars['error']) && Configure::read('debug')) { $data['exception'] = ['class' => get_class($viewVars['error']), 'code' => $viewVars['error']->getCode(), 'message' => $viewVars['error']->getMessage()]; if (!isset($data['trace'])) { $data['trace'] = Debugger::formatTrace($viewVars['error']->getTrace(), ['format' => 'array', 'args' => false]); } } return $data; }
/** * Make tasks callable * * @return void */ public function main() { if (!empty($this->params['dry-run'])) { $this->out('<warning>Dry-run mode enabled!</warning>', 1, Shell::QUIET); } $exclude = ['.git', '.svn', 'vendor', 'Vendor', 'webroot', 'tmp', 'logs']; if (empty($this->params['plugin']) && !empty($this->params['namespace']) && $this->params['namespace'] === 'App') { $exclude[] = 'plugins'; $exclude[] = 'Plugin'; } $files = $this->Stage->files($exclude); foreach ($files as $file) { $this->out(sprintf('<info>Processing %s</info>', Debugger::trimPath($file))); $this->process($file); } $this->Stage->commit(); }
/** * Stores a memory point in the internal tracker. * Takes a optional message name which can be used to identify the memory point. * If no message is supplied a debug_backtrace will be done to identify the memory point. * * @param string $message Message to identify this memory point. * @return bool */ public static function record($message = null) { $memoryUse = self::getCurrent(); if (!$message) { $trace = debug_backtrace(); $message = Debugger::trimPath($trace[0]['file']) . ' line ' . $trace[0]['line']; } if (isset(self::$_points[$message])) { $originalMessage = $message; $i = 1; while (isset(self::$_points[$message])) { $i++; $message = $originalMessage . ' #' . $i; } } self::$_points[$message] = $memoryUse; return true; }
/** * All command. * * @return void */ public function all() { if (!empty($this->params['dry-run'])) { $this->out('<warning>Dry-run mode enabled!</warning>', 1, Shell::QUIET); } $exclude = ['.git', '.svn', 'vendor', 'Vendor', 'webroot', 'tmp', 'logs']; if (empty($this->params['plugin']) && !empty($this->params['namespace']) && $this->params['namespace'] === 'App') { $exclude[] = 'plugins'; $exclude[] = 'Plugin'; } $files = $this->Stage->files($exclude); $actions = $this->_getActions(); foreach ($actions as $action) { $this->out(sprintf('<info>*** Upgrade step %s ***</info>', $action)); if (!empty($this->params['interactive'])) { $continue = $this->in('Continue with `' . $action . '`?', array('y', 'n', 'q'), 'y'); if ($continue === 'q') { return $this->error('Aborted. Changes are not commited.'); } if ($continue === 'n') { $this->out('Skipping this step.'); continue; } } foreach ($files as $file) { $this->out(sprintf('<info> * Processing %s</info>', Debugger::trimPath($file)), 1, Shell::VERBOSE); $this->{$action}->Stage = $this->Stage; $this->{$action}->process($file); if (!empty($this->params['interactive'])) { $this->Stage->commit(); $this->Stage->clear(); } } } if (empty($this->params['interactive'])) { $this->Stage->commit(); } }
public function import() { if ($this->request->is('post')) { if ($this->request->data['submissionFile'] == '') { $this->set('file_status', 'No file submitted, try again.'); } elseif ($this->request->data['submissionFile']) { $this->set('file_status', 'File submitted.'); Debugger::dump($this->request->data['submissionFile']); Debugger::dump($this->request->data['table']); if ($this->request->data['table'] == 0) { Debugger::dump($this->request->data['submissionFile']); } elseif ($this->request->data['table'] == 1) { } elseif ($this->request->data['table'] == 2) { } else { $this->Flash->error('Unexpected table value'); } $this->Flash->success('File successfully uploaded, Importing...'); } else { $this->set('file_status', 'Please submit a file.'); } } else { $this->set('file_status', 'Please submit a file.'); } }
/** * Prints out debug information about given variable. * * Only runs if debug level is greater than zero. * * @param boolean $var Variable to show debug information for. * @param boolean $showHtml If set to true, the method prints the debug data in a browser-friendly way. * @param boolean $showFrom If set to true, the method prints from where the function was called. * @return void * @link http://book.cakephp.org/2.0/en/development/debugging.html#basic-debugging * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#debug */ public static function debug($var, $showHtml = null, $showFrom = true) { if (Configure::read('debug') > 0) { // App::uses('Debugger', 'Utility'); $file = ''; $line = ''; $lineInfo = ''; if ($showFrom) { $trace = Debugger::trace(array('start' => 1, 'depth' => 2, 'format' => 'array')); $file = str_replace(array(CAKE_CORE_INCLUDE_PATH, ROOT), '', $trace[0]['file']); $line = $trace[0]['line']; } $html = <<<HTML <div class="cake-debug-output"> <pre class="cake-debug"> %s </pre> </div> HTML; $text = <<<TEXT %s ########## DEBUG ########## %s ########################### TEXT; $template = $html; if (php_sapi_name() === 'cli' || $showHtml === false) { $template = $text; if ($showFrom) { $lineInfo = sprintf('%s (line %s)', $file, $line); } } if ($showHtml === null && $template !== $text) { $showHtml = true; } $var = Debugger::exportVar($var, 25); if ($showHtml) { $template = $html; $var = htmlspecialchars($var); if ($showFrom) { $lineInfo = sprintf('<span><strong>%s</strong> (line <strong>%s</strong>)</span>', $file, $line); } } printf($template, $var); } }
/** * Start the shell and interactive console. * * @return int|void */ public function main() { $sa_table = TableRegistry::get('Friendships'); $fitbit_accounts = $sa_table->find()->matching('Froms.SocialAccounts', function ($q) { return $q->where(['provider' => 'Fitbit']); })->contain(['Tos']); $game = TableRegistry::get('Games'); $controller = new AppController(); $stream = $controller->loadComponent('Stream'); $tm_table = TableRegistry::get('TempMembers'); debug(Time::now()->i18nFormat('yyyy-MM-dd 00:00:00')); $lr_table = TableRegistry::get('LinkedRecords'); foreach ($fitbit_accounts as $fitbit_account) { //find all pairings of fitbit friends if (empty($social_accounts = $fitbit_account['to']['social_accounts'])) { continue; } $fitbit_social_account = false; foreach ($social_accounts as $social_account) { if ($social_account->provider == 'Fitbit') { $fitbit_social_account = $social_account->id; } } if (!$fitbit_social_account) { continue; } // //find todays linked record $to = $lr_table->find()->where(['social_account_id' => $fitbit_social_account, 'associated_date' => Time::now()->i18nFormat('yyyy-MM-dd 00:00:00')]); if (!$to->first()) { continue; } // // debug($to->first()); // return; $to_mem = ['member_id' => $fitbit_account->to->id, 'points' => null, 'role' => 'member', 'linked_record_id' => $to->first()->id]; if (empty($social_accounts = $fitbit_account['from']['social_accounts'])) { continue; } $fitbit_social_account = false; foreach ($social_accounts as $social_account) { if ($social_account->provider == 'Fitbit') { $fitbit_social_account = $social_account->id; } } if (!$fitbit_social_account) { continue; } $from = $lr_table->find()->where(['social_account_id' => $fitbit_social_account, 'associated_date' => Time::now()->i18nFormat('yyyy-MM-dd 00:00:00')]); if (!$from->first()) { continue; } $from_mem = ['member_id' => $fitbit_account->from->id, 'points' => null, 'role' => 'member', 'linked_record_id' => $from->first()->id]; $game_array = ['status' => 'complete', 'score_type' => 'score', 'game_type_id' => '81e376fa-9f08-4814-82e7-00a2cbf1935b', 'game_memberships' => [$to_mem, $from_mem]]; $new_game = $game->newEntity($game_array); if ($game->save($new_game)) { $base_data = $stream->_createStreamData($new_game->id, 'Game'); Debugger::log($base_data); if ($base_data) { if (!$tm_table->exists(['id' => $base_data['first_user_id']])) { $stream->_pushToStream($base_data, $base_data['first_user_id']); } if (!$tm_table->exists(['id' => $base_data['second_user_id']])) { $stream->_pushToStream($base_data, $base_data['second_user_id']); } } } } }
/** * Triggered after plugin is removed from DB and after its directory was removed. * * @param \Cake\Event\Event $event * @return void */ public function afterUninstall(Event $event) { Debugger::log('afterUninstall: ' . $this->_line()); }
/** * @param $http * @param $Notifier */ private function checkMinMaxValuesAndSendToastNotifications($Notifier, $tick_names_and_values) { $stocksAffectedMax = array(); $stocksAffectedMin = array(); $valueOfStocksAffectedMax = array(); $valueOfStocksAffectedMin = array(); for ($i = 0; $i < sizeof($tick_names_and_values); $i++) { $stockAffectedMax = $this->Stocks->find()->where(['maximum <=' => $tick_names_and_values[$i][1], 'tick_name =' => $tick_names_and_values[$i][0]])->toArray(); $stockAffectedMin = $this->Stocks->find()->where(['minimum >=' => $tick_names_and_values[$i][1], 'tick_name =' => $tick_names_and_values[$i][0]])->toArray(); for ($a = 0; $a < sizeof($stockAffectedMax); $a++) { $stocksAffectedMax[] = $stockAffectedMax[$a]; $valueOfStocksAffectedMax[] = $tick_names_and_values[$i][1]; } for ($a = 0; $a < sizeof($stockAffectedMin); $a++) { $stocksAffectedMin[] = $stockAffectedMin[$a]; $valueOfStocksAffectedMin[] = $tick_names_and_values[$i][1]; } } Debugger::dump('stocksAffectedMax: '); Debugger::dump($stocksAffectedMax); Debugger::dump('stocksAffectedMin: '); Debugger::dump($stocksAffectedMin); for ($i = 0; $i < sizeof($stocksAffectedMax); $i++) { Debugger::dump('$stocksAffectedMax[' . $i . ']'); Debugger::dump($stocksAffectedMax[$i]); $id = $stocksAffectedMax[$i]['device_id']; $device = $this->Devices->get($id, ['contain' => []]); $channelURI = $device['name']; Debugger::dump($channelURI); //$MyToastXML = '<toast><visual><binding template="ToastText02"><text id="1">'.$stocksAffectedMax[$i]['tick_name'].' atingiu máximo'.'</text><text id="2">VALOR</text></binding></visual></toast>'; //$responseToSendMsg = $Notifier->Send($channelURI, TemplateToast::ToastText01($stocksAffectedMax[$i]['tick_name'] . " atingiu máximo!")); $responseToSendMsg = $Notifier->Send($channelURI, TemplateToast::ToastText02($stocksAffectedMax[$i]['tick_name'] . " atingiu máximo!", $valueOfStocksAffectedMax[$i], TemplateToast::NotificationMail)); //$responseToSendMsg = $Notifier->Send($channelURI,$MyToastXML); Debugger::dump($responseToSendMsg); } for ($i = 0; $i < sizeof($stocksAffectedMin); $i++) { Debugger::dump('$stocksAffectedMin[' . $i . ']'); Debugger::dump($stocksAffectedMin[$i]); $id = $stocksAffectedMin[$i]['device_id']; $device = $this->Devices->get($id, ['contain' => []]); $channelURI = $device['name']; Debugger::dump($channelURI); //$MyToastXML = '<toast><visual><binding template="ToastText02"><text id="1">'.$stocksAffectedMin[$i]['tick_name'].' atingiu mínimo'.'</text><text id="2">VALOR</text></binding></visual></toast>'; //$responseToSendMsg = $Notifier->Send($channelURI, TemplateToast::ToastText01($stocksAffectedMin[$i]['tick_name'] . " atingiu mínimo!")); $responseToSendMsg = $Notifier->Send($channelURI, TemplateToast::ToastText02($stocksAffectedMin[$i]['tick_name'] . " atingiu mínimo!", $valueOfStocksAffectedMin[$i], TemplateToast::NotificationMail)); //$responseToSendMsg = $Notifier->Send($channelURI,$MyToastXML); Debugger::dump($responseToSendMsg); } }
/** * Write staged changes * * If it's a dry run though - only show what will be done, don't do anything * * @param string $path file path * @return void */ public function commit($path = null) { if (!$path) { foreach (array_keys($this->_staged['change']) as $path) { $this->commit($path); } foreach ($this->_staged['move'] as $path => $to) { if (isset($this->_staged['change'][$path])) { continue; } $this->commit($path); } foreach ($this->_staged['delete'] as $path) { $this->commit($path); } $Folder = new Folder(TMP . 'upgrade'); $Folder->delete(); return; } $dryRun = !empty($this->params['dry-run']); $isMove = isset($this->_staged['move'][$path]); $isChanged = isset($this->_staged['change'][$path]) && count($this->_staged['change'][$path]) > 1; $isDelete = in_array($path, $this->_staged['delete']); if (!$isMove && !$isChanged && !$isDelete) { return; } $gitCd = sprintf('cd %s && ', escapeshellarg(dirname($path))); if ($isDelete) { $this->out(sprintf('<info>Delete %s</info>', Debugger::trimPath($path))); if ($dryRun) { return true; } if (!empty($this->params['git'])) { exec($gitCd . sprintf('git rm -f %s', escapeshellarg($path))); return; } if (is_dir($path)) { $Folder = new Folder($path); return $Folder->delete(); } $File = new File($path, true); return $File->delete(); } if ($isMove && !$isChanged) { $to = $this->_staged['move'][$path]; $this->out(sprintf('<info>Move %s to %s</info>', Debugger::trimPath($path), Debugger::trimPath($to))); if ($dryRun || !file_exists($path)) { return true; } if (!empty($this->params['git'])) { return $this->_gitMove($gitCd, $path, $to); } if (is_dir($path)) { $Folder = new Folder($path); return $Folder->move($to); } $File = new File($to, true); return $File->write(file_get_contents($path)) && unlink($path); } $start = reset($this->_staged['change'][$path]); end($this->_staged['change'][$path]); $final = end($this->_staged['change'][$path]); $oPath = TMP . 'upgrade' . DS . $start; $uPath = TMP . 'upgrade' . DS . $final; exec('git diff --no-index ' . escapeshellarg($oPath) . ' ' . escapeshellarg($uPath), $output); $output = implode($output, "\n"); $i = strrpos($output, $final); $diff = substr($output, $i + 41); if ($isMove) { $to = $this->_staged['move'][$path]; $this->out(sprintf('<info>Move %s to %s and update</info>', Debugger::trimPath($path), Debugger::trimPath($to))); } else { $this->out(sprintf('<info>Update %s</info>', Debugger::trimPath($path))); } $this->out($diff, 1, $dryRun ? Shell::NORMAL : SHELL::VERBOSE); if ($dryRun || !file_exists($path)) { return true; } if ($isMove) { if (!empty($this->params['git'])) { $this->_gitMove($gitCd, $path, $to); } else { unlink($path); } $path = $to; } $File = new File($path, true); return $File->write(file_get_contents($uPath)); }
/** * Renders the response for the exception. * * @return \Cake\Network\Response The response to be sent. */ public function render() { $exception = $this->error; $code = $this->_code($exception); $method = $this->_method($exception); $template = $this->_template($exception, $method, $code); $unwrapped = $this->_unwrap($exception); $isDebug = Configure::read('debug'); if (($isDebug || $exception instanceof HttpException) && method_exists($this, $method)) { return $this->_customMethod($method, $unwrapped); } $message = $this->_message($exception, $code); $url = $this->controller->request->here(); if (method_exists($exception, 'responseHeader')) { $this->controller->response->header($exception->responseHeader()); } $this->controller->response->statusCode($code); $viewVars = ['message' => $message, 'url' => h($url), 'error' => $unwrapped, 'code' => $code, '_serialize' => ['message', 'url', 'code']]; if ($isDebug) { $viewVars['trace'] = Debugger::formatTrace($unwrapped->getTrace(), ['format' => 'array', 'args' => false]); $viewVars['_serialize'][] = 'trace'; } $this->controller->set($viewVars); if ($unwrapped instanceof CakeException && $isDebug) { $this->controller->set($unwrapped->getAttributes()); } return $this->_outputMessage($template); }
/** * Assert that nested anonymous timers don't get mixed up. * * @return void */ public function testNestedAnonymousTimers() { $this->assertTrue(DebugTimer::start()); usleep(100); $this->assertTrue(DebugTimer::start()); usleep(100); $this->assertTrue(DebugTimer::stop()); $this->assertTrue(DebugTimer::stop()); $timers = DebugTimer::getAll(); $this->assertEquals(3, count($timers), 'incorrect number of timers %s'); $firstTimerLine = __LINE__ - 9; $secondTimerLine = __LINE__ - 8; $file = Debugger::trimPath(__FILE__); $this->assertTrue(isset($timers[$file . ' line ' . $firstTimerLine]), 'first timer is not set %s'); $this->assertTrue(isset($timers[$file . ' line ' . $secondTimerLine]), 'second timer is not set %s'); $firstTimer = $timers[$file . ' line ' . $firstTimerLine]; $secondTimer = $timers[$file . ' line ' . $secondTimerLine]; $this->assertTrue($firstTimer['time'] > $secondTimer['time']); }
/** * Outputs a stack trace based on the supplied options. * * ### Options * * - `depth` - The number of stack frames to return. Defaults to 999 * - `args` - Should arguments for functions be shown? If true, the arguments for each method call * will be displayed. * - `start` - The stack frame to start generating a trace from. Defaults to 1 * * @param array $options Format for outputting stack trace * @return mixed Formatted stack trace */ function stackTrace(array $options = []) { if (!Configure::read('debug')) { return; } $options += ['start' => 0]; $options['start']++; echo Debugger::trace($options); }
/** * Log an error. * * @param string $level The level name of the log. * @param array $data Array of error data. * @return bool */ protected function _logError($level, $data) { $message = sprintf('%s (%s): %s in [%s, line %s]', $data['error'], $data['code'], $data['description'], $data['file'], $data['line']); if (!empty($this->_options['trace'])) { $trace = Debugger::trace(['start' => 1, 'format' => 'log']); $message .= "\nTrace:\n" . $trace . "\n"; } $message .= "\n\n"; return Log::write($level, $message); }
/** * Tests that __debugInfo is used when available * * @return void */ public function testDebugInfo() { $object = new DebuggableThing(); $result = Debugger::exportVar($object, 2); $expected = <<<eos object(Cake\\Test\\TestCase\\Error\\DebuggableThing) { \t'foo' => 'bar', \t'inner' => object(Cake\\Test\\TestCase\\Error\\DebuggableThing) {} } eos; $this->assertEquals($expected, $result); }
/** * Add an output format or update a format in Debugger. * * ``` * Debugger::addFormat('custom', $data); * ``` * * Where $data is an array of strings that use Text::insert() variable * replacement. The template vars should be in a `{:id}` style. * An error formatter can have the following keys: * * - 'error' - Used for the container for the error message. Gets the following template * variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info` * - 'info' - A combination of `code`, `context` and `trace`. Will be set with * the contents of the other template keys. * - 'trace' - The container for a stack trace. Gets the following template * variables: `trace` * - 'context' - The container element for the context variables. * Gets the following templates: `id`, `context` * - 'links' - An array of HTML links that are used for creating links to other resources. * Typically this is used to create javascript links to open other sections. * Link keys, are: `code`, `context`, `help`. See the js output format for an * example. * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following * template variables: `reference`, `path`, `line` * * Alternatively if you want to use a custom callback to do all the formatting, you can use * the callback key, and provide a callable: * * ``` * Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']]; * ``` * * The callback can expect two parameters. The first is an array of all * the error data. The second contains the formatted strings generated using * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace` * will be present depending on the other templates in the format type. * * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for * straight HTML output, or 'txt' for unformatted text. * @param array $strings Template strings, or a callback to be used for the output format. * @return array The resulting format string set. */ public static function addFormat($format, array $strings) { $self = Debugger::getInstance(); if (isset($self->_templates[$format])) { if (isset($strings['links'])) { $self->_templates[$format]['links'] = array_merge($self->_templates[$format]['links'], $strings['links']); unset($strings['links']); } $self->_templates[$format] = $strings + $self->_templates[$format]; } else { $self->_templates[$format] = $strings; } return $self->_templates[$format]; }
/** * Tests that the stackTrace() method is a shortcut for Debugger::trace() * * @return void */ public function testStackTrace() { ob_start(); list($r, $expected) = [stackTrace(), \Cake\Error\Debugger::trace()]; $result = ob_get_clean(); $this->assertEquals($expected, $result); $opts = ['args' => true]; ob_start(); list($r, $expected) = [stackTrace($opts), \Cake\Error\Debugger::trace($opts)]; $result = ob_get_clean(); $this->assertEquals($expected, $result); }
public function ajaxResponseStatusCallback($uniqueId) { try { $DEFAULT_URL = 'https://ens.firebaseio.com/'; $DEFAULT_TOKEN = Configure::read('Firebase.token'); $DEFAULT_PATH = '/call'; $firebase = new \Firebase\FirebaseLib($DEFAULT_URL, $DEFAULT_TOKEN); $sendQueueTable = TableRegistry::get('SendQueues'); $sendQueue = $sendQueueTable->find()->where(['unique_id' => $uniqueId])->contain(['Audios']); if (!$sendQueue->count()) { throw new Exception('Cannot find queue.'); } $queue = $sendQueue->all()->first(); // Get number id $numberId = $firebase->get($DEFAULT_PATH . '/' . $queue->send_queue_id . '/number_match/' . $this->request->data['CallSid']); // Set as Success $firebase->set($DEFAULT_PATH . '/' . $queue->send_queue_id . '/numbers/' . $numberId . '/call_status', 3); Debugger::log($this->request->data); $response['status'] = 1; } catch (\Exception $ex) { $response['status'] = 0; $response['message'] = $ex->getMessage(); } $this->set(compact('response')); $this->set('_serialize', ['response']); }
/** * Display an error. * * Template method of BaseErrorHandler. * * Only when debug > 2 will a formatted error be displayed. * * @param array $error An array of error data. * @param bool $debug Whether or not the app is in debug mode. * @return void */ protected function _displayError($error, $debug) { if (!$debug) { return; } Debugger::getInstance()->outputError($error); }
/** * exec method * * @param mixed $cmd '' * @param mixed &$out null * @return bool True if successful */ protected function _exec($cmd, &$out = null) { if (DS === '/') { $_out = exec($cmd . ' 2>&1', $out, $return); } else { $_out = exec($cmd, $out, $return); } if (Configure::read('debug')) { $source = Debugger::trace(array('depth' => 1, 'start' => 2)) . "\n"; //Log::write('system_calls_' . date('Y-m-d'), "\n" . $source . Debugger::exportVar(compact('cmd','out','return'))); //Log::write('system_calls', "\n" . $source . Debugger::exportVar(compact('cmd','out','return'))); } if ($return) { return false; } return $_out ? $_out : true; }
/** * Prints out debug information about given variable. * * Only runs if debug level is greater than zero. * * @param mixed $var Variable to show debug information for. * @param bool|null $showHtml If set to true, the method prints the debug data in a browser-friendly way. * @param bool $showFrom If set to true, the method prints from where the function was called. * @return void * @link http://book.cakephp.org/3.0/en/development/debugging.html#basic-debugging * @link http://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#debug */ public static function debug($var, $showHtml = null, $showFrom = true) { if (!Configure::read('debug')) { return; } $file = ''; $line = ''; $lineInfo = ''; if ($showFrom) { $trace = Debugger::trace(['start' => 1, 'depth' => 2, 'format' => 'array']); $search = [ROOT]; if (defined('CAKE_CORE_INCLUDE_PATH')) { array_unshift($search, CAKE_CORE_INCLUDE_PATH); } $file = str_replace($search, '', $trace[0]['file']); $line = $trace[0]['line']; } $html = <<<HTML <pre class="cake-debug"> %s </pre> </div> HTML; $text = <<<TEXT %s ########## DEBUG ########## %s ########################### TEXT; $template = $html; if (PHP_SAPI === 'cli' || $showHtml === false) { $template = $text; if ($showFrom) { $lineInfo = sprintf('%s (line %s)', $file, $line); } } if ($showHtml === null && $template !== $text) { $showHtml = true; } $var = Debugger::exportVar($var, 25); if ($showHtml) { $template = $html; $var = h($var); if ($showFrom) { $lineInfo = sprintf('<span><strong>%s</strong> (line <strong>%s</strong>)</span>', $file, $line); } } printf($template, $var); }