/** * Render debug trace * * @param Charcoal_String $title title */ public function render($e) { // Charcoal_ParamTrait::validateException( 1, $e ); if (!$this->renderers) { $this->renderers = array(); if (!$this->sandbox->isLoaded()) { return; } // Create Debug Trace Renderer $debugtrace_renderers = $this->sandbox->getProfile()->getArray('DEBUGTRACE_RENDERER'); if ($debugtrace_renderers) { foreach ($debugtrace_renderers as $renderer_name) { if (strlen($renderer_name) === 0) { continue; } try { $renderer = $this->sandbox->createObject($renderer_name, 'debugtrace_renderer', array(), 'Charcoal_IDebugtraceRenderer'); $this->renderers[] = $renderer; } catch (Exception $e) { _catch($e); echo "debugtrace_renderer creation failed:{$e}"; } } } } $result = b(FALSE); foreach ($this->renderers as $renderer) { $ret = $renderer->render($e); if ($ret === TRUE || $ret instanceof Charcoal_Boolean && $ret->isTrue()) { $result = b(TRUE); } } return $result; }
/** * execute exception handlers * * @param Exception $e exception to handle * * @return boolean TRUE means the exception is handled, otherwise FALSE */ public function handleException($e) { Charcoal_ParamTrait::validateException(1, $e); log_info("system, debug", "exception", "handled a framework exception!"); try { /** @var Charcoal_IDebugtraceRenderer $renderer */ $renderer = $this->getSandbox()->createObject('console', 'debugtrace_renderer', array(), 'Charcoal_IDebugtraceRenderer'); // Render exception $renderer->render($e); return TRUE; } catch (Exception $e) { _catch($e); log_info("system, debug", "exception", "debugtrace_renderer creation failed."); } return FALSE; }
public static function loadModule($sandbox, $module_path, $task_manager) { // Charcoal_ParamTrait::validateSandbox( 1, $sandbox ); // Charcoal_ParamTrait::validateStringOrObjectPath( 2, $module_path ); // Charcoal_ParamTrait::validateImplements( 3, 'Charcoal_ITaskManager', $task_manager ); try { log_debug('debug, event', "loading module: {$module_path}"); if ($module_path instanceof Charcoal_ObjectPath) { $module_path = $module_path->toString(); } else { $module_path = us($module_path); } // check if module is already loaded if (isset(self::$loaded_paths[$module_path])) { log_warning('system, event, debug', "module[{$module_path}] is already loaded."); return; } /** @var Charcoal_IModule $module */ /** @var Charcoal_Sandbox $sandbox */ $module = $sandbox->createObject($module_path, 'module', array(), 'Charcoal_IModule', 'Charcoal_SimpleModule'); // load module tasks $loaded_tasks = $module->loadTasks($task_manager); // load module events source code $loaded_events = $module->loadEvents($task_manager); // if no tasks or events are loaded, you maybe passed a wrong module path if (empty($loaded_tasks) && empty($loaded_events)) { _throw(new Charcoal_ModuleLoaderException($module_path, "no tasks and events are loaded.")); } // load required modules $required_modules = $module->getRequiredModules(); if ($required_modules) { $loaded_modules = NULL; foreach ($required_modules as $module_name) { if (strlen($module_name) === 0) { continue; } self::loadModule($sandbox, $module_name, $task_manager); } } self::$loaded_paths[$module_path] = $module_path; log_debug('debug, event, module', "loaded module: {$module_path}"); } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_ModuleLoaderException($module_path, "failed to load module.", $ex)); } }
public function setLayoutManager($layout_manager) { if ($layout_manager === NULL || $layout_manager instanceof Charcoal_ILayoutManager) { $this->layout_manager = $layout_manager; } elseif (is_string($layout_manager) || $layout_manager instanceof Charcoal_String) { $layout_manager = s($layout_manager); if ($layout_manager->isEmpty()) { $this->layout_manager = NULL; } else { try { $this->layout_manager = $this->getSandbox()->createObject($layout_manager, 'layout_manager'); } catch (Exception $e) { _catch($e); _throw(new Charcoal_LayoutManagerCreationException($layout_manager, $e)); } } } }
/** * execute exception handlers * * @param Exception $e exception to handle * * @return boolean TRUE means the exception is handled, otherwise FALSE */ public function handleException($e) { Charcoal_ParamTrait::validateException(1, $e); log_info('system, debug', "handled a framework exception!", 'exception_handler'); // Create Debug Trace Renderer try { $debugtrace_renderer = $this->getSandbox()->createObject('html', 'debugtrace_renderer', array(), 'Charcoal_IDebugtraceRenderer'); log_info('system, debug', "debugtrace_renderer[{$debugtrace_renderer}] created.", 'exception_handler'); // Render exception $error_html = $debugtrace_renderer->output($e); log_info('system, debug', "debugtrace_renderer[{$debugtrace_renderer}] output html.", 'exception_handler'); // generate error dump(HTML) log_error('error_dump', $error_html, 'exception_handler'); log_info('system, debug', "error_html:\n{$error_html}", 'exception_handler'); return TRUE; } catch (Exception $e) { _catch($e); log_info('system, debug', "debugtrace_renderer[{$debugtrace_renderer}] creation failed.", 'exception_handler'); } return FALSE; }
/** * write session data */ public function write($id, $sess_data) { $criteria = new Charcoal_SQLCriteria(s('session_id = ?'), v(array($id))); $dto = $this->gw->findFirst(qt($this->target), $criteria); if (!$dto) { $dto = new Charcoal_SessionTableDTO(); $dto->session_id = $id; $dto->save_path = $this->save_path; $dto->session_name = $this->session_name; } $dto->session_data = $sess_data; try { $this->gw->beginTrans(); $this->gw->save(s($this->target), $dto); $this->gw->commitTrans(); } catch (Exception $ex) { _catch($ex); $this->gw->rollbackTrans(); _throw(new Charcoal_SessionHandlerException('write failed', $ex)); } return true; }
public function createFile($file_path, $contents, $overwrite = TRUE, $mode = 0777) { Charcoal_ParamTrait::validateString(1, $file_path); Charcoal_ParamTrait::validateString(2, $contents); Charcoal_ParamTrait::validateBoolean(3, $overwrite); Charcoal_ParamTrait::validateInteger(4, $mode); $obj = new Charcoal_File($file_path, $this->_base_dir_obj); if ($overwrite) { if ($obj->exists() && !$obj->canWrite()) { _throw(new Charcoal_FileSystemComponentException('specified file is not writeable.')); } } elseif ($obj->exists()) { _throw(new Charcoal_FileSystemComponentException('specified file is already exists.')); } try { // create file with parent directory $obj->makeFile($mode, $contents, TRUE); return $obj; } catch (Exception $e) { _catch($e); _throw(new Charcoal_FileSystemComponentException(s('creating file failed.'), $e)); } }
/** * Framework global exception handler * * @param Exception $e */ public static function onUnhandledException($e) { _catch($e); log_fatal("system,error", "charcoal_global_exception_handler:" . $e->getMessage()); Charcoal_Framework::handleException($e); }
<?php def_printfer('puts', "%s\n"); puts('base>'); _catch("first", function () { puts('1>'); _catch("second", function () { puts('2>'); _catch("third", function () { puts('3>'); _throw("second"); puts('<3'); }); puts('<2'); }); puts('<1'); }); puts('<base'); ?> --- base> 1> 2> 3> <1 <base
public function generate($sequence) { Charcoal_ParamTrait::validateIsA(1, 'Charcoal_ISequence', $sequence); try { $token_key = $this->token_key; // get token container from session. $token_list = $sequence->get($token_key); if ($token_list === NULL || !is_array($token_list)) { $token_list = array(); } // Generate token $new_token = $this->token_generator->generateToken(); log_debug("debug", "token generated: {$new_token}"); // add new token to token list. $token_list[] = $new_token; log_debug("debug", "token_list: ", print_r($token_list, true)); // save token list in sequence. $sequence->set($token_key, $token_list); log_debug("debug", "sequence: " . print_r($sequence, true)); return $new_token; } catch (Exception $e) { _catch($e); _throw(new Charcoal_FormTokenComponentException(s(__CLASS__ . '#' . __METHOD__ . ' failed.'), $e)); } }
/** * Set cache data * * @param Charcoal_String $key string name to identify cached data * @param Charcoal_Object $value cache data to save */ public function setCache($key, $value) { // Charcoal_ParamTrait::validateString( 1, $key ); try { Charcoal_Cache::set($key, $value); } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_EventContextException(__METHOD__ . '() failed.', $ex)); } }
/** * Prepare for statement and execute query * * @param string|Charcoal_String $sql SQL statement(placeholders can be included) * @param array|Charcoal_HashMap $params Parameter values for prepared statement * @param array|Charcoal_HashMap $driver_options Driver options * * @return PDOStatement */ public function prepareExecute($sql, $params = NULL, $driver_options = NULL) { $result = null; try { // 接続処理 $this->connect(); // statementの実行 $result = $this->_prepareExecute($sql, $params, $driver_options); } catch (Exception $e) { _catch($e); $msg = __METHOD__ . ' failed:'; $msg .= ' [SQL]' . $sql; $msg .= ' [params]' . ($params ? v($params)->join(',', TRUE) : ''); $msg .= ' [message]' . $e->getMessage(); log_error('data_source,sql,debug', $msg, self::TAG); _throw(new Charcoal_DBDataSourceException($msg, $e)); } return $result; }
/** * create directory * * @return Charcoal_File file object of created directory */ public function create() { try { $obj = new Charcoal_File(s($this->_dir_path)); $obj->makeDirectory($this->_mode, b(TRUE)); return $obj; } catch (Exception $e) { _catch($e); _throw(new Charcoal_TempDirComponentException(s('creating directory failed.'), $e)); } }
/** * @name multi_curl * curl并发封装函数 * @param curl_opt(url,request,header,user_agent,cookie,cookiejar,cookie_file) * @param request_type define(GET,POST) * @param timeout int */ function multi_curl($curl_opt, $request_type = 'GET', $timeout = '10') { $multi_handler = curl_multi_init(); $thread_number = count($curl_opt); $i = 0; for ($i; $i < $thread_number; $i++) { $curl_handler[$i] = curl_init(); is_array($curl_opt[$i]['header']) ? curl_setopt($curl_handler[$i], CURLOPT_HTTPHEADER, $curl_opt[$i]['header']) : FALSE; if ('POST' === $request_type) { curl_setopt($curl_handler[$i], CURLOPT_URL, $curl_opt[$i]['url']); curl_setopt($curl_handler[$i], CURLOPT_POST, 1); curl_setopt($curl_handler[$i], CURLOPT_POSTFIELDS, $curl_opt[$i]['request']); } else { curl_setopt($curl_handler[$i], CURLOPT_URL, $curl_opt[$i]['url'] . '?' . $curl_opt[$i]['request']); } $curl_opt[$i]['user_agent'] ? curl_setopt($curl_handler[$i], CURLOPT_USERAGENT, $curl_opt[$i]['user_agent']) : curl_setopt($curl_handler[$i], CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); $curl_opt[$i]['referer'] ? curl_setopt($curl_handler[$i], CURLOPT_REFERER, $curl_opt[$i]['referer']) : curl_setopt($curl_handler[$i], CURLOPT_AUTOREFERER, 1); if ($curl_opt[$i]['cookie']) { curl_setopt($curl_handler[$i], CURLOPT_COOKIE, $curl_opt[$i]['cookie']); } if ('COOKIEJAR' === $curl_opt[$i]['cookiejar']) { $curl_opt[$i]['cookie_file'] = COOKIE_PATH . $curl_opt[$i]['cookie_file']; curl_setopt($curl_handler[$i], CURLOPT_COOKIEJAR, $curl_opt[$i]['cookie_file']); curl_setopt($curl_handler[$i], CURLOPT_COOKIEFILE, $curl_opt[$i]['cookie_file']); } curl_setopt($curl_handler[$i], CURLOPT_TIMEOUT, $timeout); curl_setopt($curl_handler[$i], CURLOPT_RETURNTRANSFER, 1); curl_multi_add_handle($multi_handler, $curl_handler[$i]); } try { do { $exec_handler = curl_multi_exec($multi_handler, $active); //当无数据时或请求暂停时,active=true } while ($exec_handler == CURLM_CALL_MULTI_PERFORM); //当正在接受数据时 while ($active and $exec_handler == CURLM_OK) { //当无数据时或请求暂停时,active=true,为了减少cpu的无谓负担,这一步很难明啊 if (curl_multi_select($multi_handler) != -1) { do { $exec_handler = curl_multi_exec($multi_handler, $active); if (!isset($exec_handler)) { _throw('500'); } } while ($exec_handler == CURLM_CALL_MULTI_PERFORM); } } $response = []; foreach ($curl_handler as $key => $value) { $response[] = ['status_code' => curl_getinfo($value, CURLINFO_HTTP_CODE), 'response' => curl_multi_getcontent($value)]; curl_close($curl_handler[$key]); //关闭所有对象 curl_multi_remove_handle($multi_handler, $curl_handler[$key]); //用完马上释放资源 } curl_multi_close($multi_handler); unset($multi_handler); unset($curl_handler); return $response; } catch (Exception $e) { _catch($e); } }
public function prepareExecute(Charcoal_String $sql, Charcoal_Vector $params = NULL) { $flag = new Charcoal_ErrorReportingSwitcher(0, E_DEPRECATED); $result = null; // 接続処理 $this->connect(); try { // statementの実行 $result = $this->_prepareExecute($sql, $params); } catch (Exception $e) { _catch($e); _throw(new Charcoal_DBDataSourceException(__METHOD__ . " failed: [SQL]{$sql} [params]{$params}", $e)); } return $result; }
/** * Execute TRUNCATE TABLE sql * * @param Charcoal_String|string|NULL $comment comment text * @param string $model_name * * @return int */ public function truncateTable($comment, $model_name) { if ($comment === NULL) { list($file, $line) = Charcoal_System::caller(0); $comment = basename($file) . '(' . $line . ')'; } try { return $this->impl->truncateTable($comment, $model_name); } catch (Exception $e) { _catch($e, TRUE); _throw(new Charcoal_DBException(__METHOD__ . " Failed.", $e)); } return 0; }
/** * Get element value as file size * * @param string $key Key string to get * @param float $default_value default value * * @return integer */ public function getSize($key, $default_value = NULL) { $value = NULL; try { $value = parent::getSize($key, $default_value); } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_ProfileConfigException($key, __METHOD__ . '() failed.', $ex)); } return $value; }
/** * create file * * @param string|Charcoal_String $contents * @param Charcoal_File $dir * @param string|Charcoal_String $file_name * * @return Charcoal_File */ public function create($contents, $dir = null, $file_name = null) { if ($file_name === null) { $tmp_filename = Charcoal_System::hash() . '.tmp'; } if ($dir === null) { $dir = Charcoal_ResourceLocator::getFile($this->getSandbox()->getEnvironment(), "%TMP_DIR%"); } $tmp_file = new Charcoal_File($file_name, $dir); if ($tmp_file->isDirectory()) { _throw(new Charcoal_FileSystemComponentException('specified path is directory.')); } if ($tmp_file->exists()) { _throw(new Charcoal_FileSystemComponentException('specified file is already exists.')); } if ($this->overwrite) { if ($tmp_file->exists() && !$tmp_file->canWrite()) { _throw(new Charcoal_FileSystemComponentException('specified file is not writeable.')); } } try { // create file $tmp_file->makeFile($this->mode, $contents, TRUE); $this->file = $tmp_file; return $tmp_file; } catch (Exception $e) { _catch($e); _throw(new Charcoal_TempFileComponentException(s('creating file failed.'), $e)); } return null; }
/** * process events * * @param Charcoal_IEventContext $context * * @return int * * @throws Charcoal_BusinessException|Charcoal_RuntimeException */ public function processEvents($context) { $debug = $this->getSandbox()->isDebug() || $context->getProcedure()->isDebugMode(); if ($debug) { log_debug('system,event', "processEvents start."); } // $procedure = $context->getProcedure(); // $request = $context->getRequest(); // $sequence = $context->getSequence(); // $response = $context->getResponse(); $max_event_loop = $this->max_event_loop; $exit_code = 0; try { $queue = $this->queue; $timer_all = Charcoal_Benchmark::start(); $loop_id = 0; while (!$queue->isEmpty()) { if ($debug) { log_debug('system,event', "event queue(" . count($queue) . "): {$queue}"); } // increment loop counter $loop_id++; // イベント一覧を優先度でソートする $queue->sortByPriority(); /** @var Charcoal_IEvent $event */ $event = $queue->dequeue(); /** @var string $event_name */ $event_name = $event->getObjectName(); /** @var Charcoal_ObjectPath $event_id */ $event_id = $event->getObjectPath(); $delete_event = FALSE; $context->setEvent($event); // if this event loop exceeds [max_event_loop], thro exception if ($loop_id > $max_event_loop) { log_warning("system,event", "[loop:{$loop_id}/{$event_name}] aborting by overflow maximum loop count[{$max_event_loop}].", "task_manager"); log_warning("system,event", "[loop:{$loop_id}/{$event_name}] event queue=[{$queue}].", "task_manager"); _throw(new Charcoal_EventLoopCounterOverflowException($max_event_loop)); } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event loop start."); } // タスク一覧を優先度でソートする $key_priority = array(); foreach ($this->tasks as $key => $task) { $key_priority[$key] = ui($task->getPriority()); } $a_task_list = uv($this->tasks); array_multisort($key_priority, SORT_DESC, $a_task_list); $this->tasks = v($a_task_list); // task list to remove on end of this loop $remove_tasks = NULL; // すべてのタスクにイベントをディスパッチする if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] task list: [{$this->tasks}]"); } foreach ($this->tasks as $task) { $task_name = $task->getObjectName(); $task_id = $task->getObjectPath(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is dispatching to task[{$task_name}]."); } // イベントフィルタ $process = FALSE; $event_filters = $task->getEventFilters(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task event filter: " . $event_filters); } foreach ($event_filters as $filter) { if ($event_id->getObjectPathString() == us($filter)) { $process = TRUE; break; } } if (!$process) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is NOT found in task's event filters: [{$event_filters}]. Passing this task."); } continue; } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is found in task's event filters: [{$event_filters}]."); } // task timer start $timer_task = Charcoal_Benchmark::start(); $result = NULL; try { $result = $task->processEvent($context); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] returned from processEvent with result:" . print_r($result, true)); } } catch (Charcoal_BusinessException $e) { // just handle the exception $exception_handled = $task->handleException($e, $context); if (b($exception_handled)->isFalse()) { // just re-throw the exception, if the exception was not handled by the task throw $e; } } catch (Charcoal_RuntimeException $e) { // write log and handle the exception _catch($e); $exception_handled = $task->handleException($e, $context); if (b($exception_handled)->isFalse()) { // write log and re-throw the exception, if the exception was not handled by the task _throw($e); } } // result value handling $result_str = NULL; if ($result === NULL) { $result_str = 'NULL'; } elseif ($result === FALSE || $result instanceof Charcoal_Boolean && $result->isFalse()) { $result_str = 'FALSE'; $result = FALSE; } elseif ($result === TRUE || $result instanceof Charcoal_Boolean && $result->isTrue()) { $result_str = 'TRUE'; $result = TRUE; } else { $msg = "processEvent() must return a [boolean] value. but returned:" . print_r($result, true); log_error('system,event,error', $msg, self::TAG); _throw(new Charcoal_ProcessEventAtTaskException($event, $task, $result, $msg)); } // task timer stop $elapse = Charcoal_Benchmark::stop($timer_task); log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event was processed by task. result=[{$result_str}] time=[{$elapse}]msec."); // ポストアクション $post_actions = $task->getPostActions(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task post actions: {$post_actions}"); } if ($result && $post_actions) { foreach ($post_actions as $key => $action) { $target = NULL; $action = us($action); if (strpos(":", $action) !== FALSE) { list($action, $target) = explode(":", trim($action)); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] post action[{$action}] with target[{$target}]."); } } else { $action = trim($action); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] post action[{$action}]."); } } switch ($action) { case "remove_task": // タスク実行リストからタスクを削除 if (!$target) { $target = $task_id; } if ($target == $task_id) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task[{$target}] is marked to remove."); } $remove_tasks[] = $task_id; } break; case "remove_event": // イベントを削除 if (!$target) { $target = $event_id; } if ($target == $event_id) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$target}] is marked to remove."); } $delete_event |= TRUE; } break; case "continue_event": // イベントをキューに再投入 break; } } } else { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] no post action is defined for event."); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] task loop end."); } } // task loop end // remove tasks if ($remove_tasks) { foreach ($remove_tasks as $task_id) { unset($this->tasks["{$task_id}"]); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] removed task: {$task_id}"); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] next task list: [{$this->tasks}]"); } } if (!$delete_event) { // push back the event into our event queue $this->pushEvent($event); } else { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event[{$event}] is removed."); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event loop end."); } } // event loop end if ($queue->isEmpty()) { if ($debug) { log_debug('system,event', "event queue is empty."); } $exit_code = Charcoal_Event::EXIT_CODE_OK; } // ログ $elapse = Charcoal_Benchmark::stop($timer_all); if ($debug) { log_debug('system,event', "event loop end. time=[{$elapse}]msec."); } } catch (Charcoal_RuntimeException $e) { _catch($e, true); if ($debug) { log_debug('system,event,debug', "an exception occured while processing event."); } _throw(new Charcoal_ProcessEventAtTaskManagerException($e)); } if ($debug) { log_debug('system,event', "processEvents end: exit_code=" . print_r($exit_code, true)); } return $exit_code; }
/** * load component * * @param string $component_name component path * @param Charcoal_Vector $args constructor arguments */ public function loadComponent($component_name, $args = array()) { try { $component_name = us($component_name); // log_info( "system,container", "container", "Loading component: [$component_name]"); // コンポーネント設定ファイルの読み込み $obj_path = new Charcoal_ObjectPath($component_name); $config = Charcoal_ConfigLoader::loadConfig($this->sandbox, $obj_path, 'component'); $config = new Charcoal_Config($this->sandbox->getEnvironment(), $config); // キャッシュに保存 $this->component_configs[$component_name] = $config; // クラス名を取得 $class_name = $config->getString('class_name'); if ($class_name === NULL) { _throw(new Charcoal_ComponentConfigException($component_name, "class_name", "mandatory")); } // create class object $klass = new Charcoal_Class($class_name); // コンポーネントスコープを取得 $scope = $config->getString('scope', self::SCOPE_REQUEST); $scope = us($scope); // コンポーネントスコープによって生成方法を変更 $component = NULL; switch ($scope) { case self::SCOPE_SESSION: // コンポーネントのインスタンスをセッションから復元 $component = unserialize($_SESSION[$component_name]); // セッションになければ、インスタンスを生成 if ($component == NULL) { $component = $klass->newInstance($args); } break; case self::SCOPE_TRANSIENT: case self::SCOPE_REQUEST: // コンポーネントのインスタンス生成 $component = $klass->newInstance($args); break; default: // scopeに指定されたワードが不正 _throw(new Charcoal_ComponentConfigException($component_name, 'scope', "invalid scope value:{$scope}")); break; } // initialize component $component->setComponentName($component_name); $component->setSandbox($this->sandbox); // 生成したインスタンスがIComponentインタフェースを実装しているか確認 if (!$component instanceof Charcoal_IComponent) { // 実装例外 _throw(new Charcoal_InterfaceImplementException($class_name, "Charcoal_IComponent")); } // コンポーネントを初期化 // log_info( "system,container", "container", "configuring component: [$component_name]"); $component->configure($config); // コンポーネントを配列に登録 if ($scope == self::SCOPE_SESSION || $scope == self::SCOPE_REQUEST) { $this->components[$component_name] = $component; } // log_info( "system,container", "container", "loaded component: [$component_name]"); // ロードしたコンポーネントを返却 return $component; } catch (Exception $ex) { _catch($ex); // rethrow exception _throw(new Charcoal_ComponentLoadingException($component_name, $ex)); } }
/** * real implementation of Charcoal_SmartGateway::save() * * @param Charcoal_String|string $comment comment text * @param Charcoal_QueryTarget $query_target description about target model, alias, or joins * @param Charcoal_DTO $data associative DTO object to insert * * @return int last inserted id */ public function save($comment, $query_target, $data) { Charcoal_ParamTrait::validateString(1, $comment, TRUE); Charcoal_ParamTrait::validateIsA(2, 'Charcoal_QueryTarget', $query_target); Charcoal_ParamTrait::validateDTO(3, $data); $new_id = 0; try { $model = $this->getModel($query_target->getModelName()); $alias = $query_target->getAlias(); // primary key $pk = $model->getPrimaryKey(); // validate primary key value $valid = $model->validatePrimaryKeyValue($data); if ($valid) { // find entity $obj = self::findById($comment, $query_target, $data->{$pk}); // if not found, dto is regarded as a new entity $is_new = empty($obj); } else { // if promary key value is invalid, dto id rebgarded as a new entity $is_new = true; } // build SQL if (!$is_new) { // UPDATE $data_id = $data[$pk]; $where = "{$pk} = ?"; $params = array(ui($data_id)); $criteria = new Charcoal_SQLCriteria($where, $params); list($sql, $params) = $this->sql_builder->buildUpdateSQL($model, $alias, $data, $criteria); } else { // INSERT list($sql, $params) = $this->sql_builder->buildInsertSQL($model, $alias, $data); $is_new = TRUE; } $sql = !empty($comment) ? $this->sql_builder->prependComment($sql, $comment) : $sql; $this->data_source->prepareExecute($sql, $params); if ($is_new) { $sql = $this->sql_builder->buildLastIdSQL(); $result = $this->data_source->prepareExecute($sql); $row = $this->data_source->fetchArray($result); $new_id = $row[0]; } else { $new_id = $data[$pk]; } log_debug("debug,smart_gateway,sql", "new_id:{$new_id}", self::TAG); } catch (Exception $e) { _catch($e); _throw(new Charcoal_DBException(__METHOD__ . " Failed.", $e)); } return $new_id; }
/** * create class loader * * @param string $obj_path class loader's object path to create * * @return Charcoal_IClassLoader class loader object */ public function createClassLoader($obj_path) { // Charcoal_ParamTrait::validateStringOrObjectPath( 1, $obj_path ); $class_loader = NULL; try { $obj_path = is_string($obj_path) ? new Charcoal_ObjectPath($obj_path) : $obj_path; // Configをロード $config = Charcoal_ConfigLoader::loadConfig($this, $obj_path, 'class_loader'); $config = new Charcoal_Config($this->environment, $config); // クラス名を取得 $class_name = $config->getString('class_name'); if ($class_name === NULL) { _throw(new Charcoal_ClassLoaderConfigException($obj_path, 'class_name', 'mandatory')); } $class_name = us($class_name); // project directory $project_dir = Charcoal_ResourceLocator::getProjectPath(); // ソースの取り込み $source_path = $project_dir . '/app/' . CHARCOAL_APPLICATION . '/class/class_loader/' . $class_name . '.class.php'; if (is_readable($source_path)) { /** @noinspection PhpIncludeInspection */ include $source_path; } else { $source_path = $project_dir . '/class/class_loader/' . $class_name . '.class.php'; if (is_readable($source_path)) { /** @noinspection PhpIncludeInspection */ include $source_path; } } // クラスローダのインスタンス生成 $klass = new Charcoal_Class($class_name); /** @var Charcoal_IClassLoader $class_loader */ $class_loader = $klass->newInstance(); $class_loader->setSandbox($this); // インタフェース確認 $interface = new Charcoal_Interface('Charcoal_IClassLoader'); $interface->validateImplements($class_loader); // log_info( 'system', "factory", "クラスローダ[" . us($object_path) . "]を作成しました。" ); } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_CreateClassLoaderException($obj_path, $ex)); } return $class_loader; }
public function connect($force = FALSE) { // 接続済みなら何もしない if ($this->connected && !$force) { return; } $db_file = $this->db_file; try { $sqliteerror = ''; $this->connection = sqlite_open($db_file, 0666, $sqliteerror); } catch (Exception $e) { _catch($e); _throw(new Charcoal_DBConnectException(__METHOD__ . " failed: [db_string]{$db_string}", $e)); } }
/** * Process events * * @param Charcoal_IEventContext $context event context * * @return boolean */ public function processEvent($context) { log_debug("smarty", "smarty=" . spl_object_hash($this->smarty), self::TAG); /** @var Charcoal_RenderLayoutEvent $event */ $event = $context->getEvent(); /** @var Charcoal_HttpResponse $response */ $response = $context->getResponse(); $sequence = $context->getSequence(); // output response headers // $response->flushHeaders(); // retrieve layout $layout = $event->getLayout(); log_debug("smarty", "Rendering by smarty. Layout:" . print_r($layout, true), self::TAG); log_debug("smarty", "caching=" . print_r($this->smarty->caching, true), self::TAG); log_debug("smarty", "template_dir=" . print_r($this->smarty->template_dir, true), self::TAG); log_debug("smarty", "compile_dir=" . print_r($this->smarty->compile_dir, true), self::TAG); log_debug("smarty", "config_dir=" . print_r($this->smarty->config_dir, true), self::TAG); log_debug("smarty", "cache_dir=" . print_r($this->smarty->cache_dir, true), self::TAG); log_debug("smarty", "plugins_dir=" . print_r($this->smarty->plugins_dir, true), self::TAG); $error_handler_old = NULL; try { $charcoal = array(); // page redirection if ($layout instanceof Charcoal_IRedirectLayout) { $url = $layout->makeRedirectURL(); $response->redirect(s($url)); log_debug("system, debug, smarty, redirect", "redirected to URL: {$url}", self::TAG); } elseif ($event instanceof Charcoal_URLRedirectEvent) { /** @var Charcoal_URLRedirectEvent $event */ $url = $event->getURL(); $response->redirect(s($url)); log_debug("system, debug, smarty, redirect", "redirected to URL: {$url}", self::TAG); } elseif ($event instanceof Charcoal_RenderLayoutEvent) { // Page information $page_info = $layout->getAttribute(s('page_info')); log_debug("smarty", "page_info=" . print_r($page_info, true), self::TAG); // Profile information $profile_config = $this->getSandbox()->getProfile()->getAll(); if ($profile_config && is_array($profile_config)) { foreach ($profile_config as $key => $value) { $charcoal['profile'][$key] = $value; } } // Cookie information if ($response instanceof Charcoal_HttpResponse) { $cookies = $response->getCookies(); if ($cookies && is_array($cookies)) { foreach ($cookies as $key => $value) { $charcoal['cookie'][$key] = $value; } } } $smarty = $this->smarty; // Assign variables if ($page_info && is_array($page_info)) { foreach ($page_info as $key => $value) { $smarty->assign($key, $value); } } // Sequence data $charcoal['sequence'] = $sequence; // Request ID and reauest path $charcoal['request']['id'] = $this->getSandbox()->getEnvironment()->get('%REQUEST_ID%'); $charcoal['request']['path'] = $this->getSandbox()->getEnvironment()->get('%REQUEST_PATH%'); // Assign all $smarty->assign('charcoal', $charcoal); // Assign all layout values $layout_values = $event->getValues(); if (!$layout_values) { // If layout values are not set, response values will be used instead. $layout_values = $response->getAll(); } foreach ($layout_values as $key => $value) { $smarty->assign($key, $value); } $smarty->assign('_smarty', $smarty); // render template $template = $layout->getAttribute(s('layout')); // set smarty error_reporting flags $this->smarty->error_reporting = E_ALL & ~E_STRICT & ~E_WARNING & ~E_NOTICE & ~8192; // rewrite error handler $error_handler_old = set_error_handler(array($this, "onUnhandledError")); // compile and output template log_debug("smarty", "template={$template}", self::TAG); $html = $smarty->fetch($template); log_debug("smarty", "html={$html}", self::TAG); // output to rendering target $render_target = $event->getRenderTarget(); if ($render_target) { $render_target->render($html); log_debug("smarty", "Rendered by render target: {$render_target}", self::TAG); } else { echo $html; log_debug("smarty", "Output by echo.", self::TAG); } } } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_SmartyRendererTaskException("rendering failed", $ex)); } if ($error_handler_old) { set_error_handler($error_handler_old); } return b(TRUE); }
/** * execute framework main code * * @param boolean $debug * @param Charcoal_Sandbox $sandbox */ public static function run($debug = NULL, $sandbox = NULL) { $th_run = Charcoal_Benchmark::start(); $mh_run = Charcoal_MemoryBenchmark::start(); // Charcoal_ParamTrait::validateBoolean( 1, $debug, TRUE ); // Charcoal_ParamTrait::validateSandbox( 2, $sandbox, TRUE ); if ($sandbox === NULL) { $sandbox = new Charcoal_Sandbox(CHARCOAL_PROFILE, $debug); } try { try { //ob_start(); self::_run($sandbox); //ob_end_flush(); } catch (Charcoal_ProcedureNotFoundException $ex) { _catch($ex); switch (CHARCOAL_RUNMODE) { // ランモードがhttpの時は404エラー case 'http': throw new Charcoal_HttpStatusException(404, $ex); break; // それ以外の場合はリスロー // それ以外の場合はリスロー default: _throw($ex); break; } } catch (Exception $ex) { _catch($ex); switch (CHARCOAL_RUNMODE) { // ランモードがhttpの時は500エラー case 'http': throw new Charcoal_HttpStatusException(500, $ex); break; // それ以外の場合はリスロー // それ以外の場合はリスロー default: _throw($ex); break; } } } catch (Charcoal_ProfileLoadingException $e) { echo 'profile loading failed:' . $e->getMessage(); exit; } catch (Exception $e) { _catch($e); // restore error handlers for avoiding infinite loop restore_error_handler(); restore_exception_handler(); self::handleException($e); // display debugtrace if ($debug || $sandbox->isDebug()) { self::$debugtrace_renderers->render($e); } self::$loggers->flush(); } catch (Throwable $e) { _catch($e); // restore error handlers for avoiding infinite loop restore_error_handler(); restore_exception_handler(); self::handleException($e); // display debugtrace if ($debug || $sandbox->isDebug()) { self::$debugtrace_renderers->render($e); } self::$loggers->flush(); } // finally process $timer_score = Charcoal_Benchmark::stop($th_run); log_debug('system, debug', sprintf("total framework process time: [%0.4f] msec", $timer_score)); // memory usage list($usage_1, $usage_2) = Charcoal_MemoryBenchmark::stop($mh_run); log_debug('system, debug', sprintf("used memory: [%d] bytes / [%d] bytes", $usage_1, $usage_2)); // memory peak usage $peak_usage_1 = Charcoal_MemoryUtil::convertSize(memory_get_peak_usage(true), Charcoal_EnumMemoryUnit::UNIT_B); $peak_usage_2 = Charcoal_MemoryUtil::convertSize(memory_get_peak_usage(false), Charcoal_EnumMemoryUnit::UNIT_B); log_debug('system, debug', sprintf("peak memory: [%d] bytes / [%d] bytes", $peak_usage_1, $peak_usage_2)); //Charcoal_Object::dump(); self::terminate(); }
/** * Process events * * @param Charcoal_IEventContext $context event context */ public function processEvent($context) { $event = $context->getEvent(); $response = $context->getResponse(); $sequence = $context->getSequence(); // output response headers $response->flushHeaders(); // retrieve layout $layout = $event->getLayout(); // log_info( "system,renderer", "Rendering by smarty. Layout:" . print_r($layout,true) ); try { $charcoal = array(); // page redirection if ($layout instanceof Charcoal_IRedirectLayout) { $url = $layout->makeRedirectURL(); $response->redirect(s($url)); // log_info( "system,renderer", "renderer", "Redirected to: $url" ); } elseif ($event instanceof Charcoal_URLRedirectEvent) { $url = $event->getURL(); $response->redirect(s($url)); // log_info( "system,renderer", "renderer", "Redirected to: $url" ); } else { // Page information $page_info = $layout->getAttribute(s('page_info')); // Profile information $profile_config = Charcoal_Profile::getConfig(); if ($profile_config && is_array($profile_config)) { foreach ($profile_config as $key => $value) { $charcoal['profile'][$key] = $value; } } // Cookie information $cookies = $response->getCookies(); if ($cookies && is_array($cookies)) { foreach ($cookies as $key => $value) { $charcoal['cookie'][$key] = $value; } } // Assign variables if ($page_info && is_array($page_info)) { foreach ($page_info as $key => $value) { ${$key} = $value; } } // Sequence data $charcoal['sequence'] = $sequence; // Request ID and reauest path $charcoal['request']['id'] = $this->getSandbox()->getEnvironment()->get('%REQUEST_ID%'); $charcoal['request']['path'] = $this->getSandbox()->getEnvironment()->get('%REQUEST_PATH%'); // Assign all //$charcoal = $charcoal; // Assign all response values $keys = $response->getKeys(); foreach ($keys as $key) { $value = $response->get(s($key)); $smarty->assign($key, $value); } // render template $template = $layout->getAttribute(s('layout')); // log_info( "smarty", "template=$template" ); $html = $smarty->fetch($template); // log_info( "smarty", "html=$html" ); echo $html; } } catch (Exception $ex) { _catch($ex); _throw(new Charcoal_SmartyRendererTaskException("rendering failed", $ex)); } return b(TRUE); }