/** * execute tests * * @param string $action * @param Charcoal_IEventContext $context * * @return boolean */ public function test($action, $context) { $action = us($action); // temp file component /** @var Charcoal_TempFileComponent $tf */ $tf = $context->getComponent('temp_file@:charcoal:file'); switch ($action) { case "create": $file = $tf->create("test"); $this->assertTrue($file->exists()); $this->assertTrue($file->canRead()); $this->assertEquals("test", $file->getContents()); return TRUE; case "get_contents": $temp_file = new Charcoal_File(CHARCOAL_TMP_DIR . '/tmpfile.txt'); $temp_file->putContents("test"); $tf->setFile($temp_file); $this->assertEquals("test", $tf->getContents()); return TRUE; case "put_contents": $temp_file = new Charcoal_File(CHARCOAL_TMP_DIR . '/tmpfile.txt'); $tf->setFile($temp_file); $tf->putContents("cat"); $this->assertTrue($temp_file->exists()); $this->assertTrue($temp_file->canRead()); $this->assertEquals("cat", $temp_file->getContents()); return TRUE; } return FALSE; }
/** * イベントを処理する * * @param Charcoal_IEventContext $context * * @return boolean */ public function processEvent($context) { $request = $context->getRequest(); // パラメータを取得 $database = us($request->getString('p2')); $table = us($request->getString('p3')); //======================================= // Confirm input parameters //======================================= if (!empty($database) && !preg_match('/^[0-9a-zA-Z_\\-]*$/', $database)) { print "Parameter 2(database name) is wrong: {$database}" . PHP_EOL; return b(true); } if (!empty($table) && !preg_match('/^[0-9a-zA-Z_\\-]*$/', $table)) { print "Parameter 3(table name) is wrong: {$table}" . PHP_EOL; return b(true); } //======================================= // Send new project event //======================================= /** @var Charcoal_IEvent $event */ $event_path = 'show_table_event@:charcoal:db:show:table'; $event = $context->createEvent($event_path, array($database, $table)); $context->pushEvent($event); return b(true); }
/** * process event * * @param Charcoal_IEventContext $context event context * * @return boolean */ public function processEvent($context) { $request = $context->getRequest(); // get command line options $cmd_path = us($request->getString('p2')); $options = array('@:help' => '[command_path]', '@:version' => '', '@:db:generate:model' => 'databse table [target directory]', '@:db:show:table' => 'databse table'); $examples1 = array('@:help' => '@:version => show "@:version" command help', '@:db:generate:model' => 'charcoal blog => generate "blog" table\'s model files in "charcoal" database' . '(model files are generated into current directory).', '@:db:show:table' => 'charcoal blog => show description about "blog" table in "charcoal" database.'); $examples2 = array('@:help' => 'list => show all supported commands("list" can be omitted)'); $descriptions = array('@:help' => 'show command help or list all command paths', '@:version' => 'show framework version.', '@:db:generate:model' => 'create model files into [target directory].', '@:db:show:table' => 'show table description'); if (empty($cmd_path) || $cmd_path == 'list') { // show all commands echo "Supported command list: "; foreach ($options as $path => $opt) { echo "\n " . $path; } } elseif (isset($options[$cmd_path])) { echo "How to use: "; echo "\n charcoal " . $cmd_path . ' ' . $options[$cmd_path]; if (isset($examples1[$cmd_path])) { echo "\nExample:"; echo "\n charcoal " . $cmd_path . ' ' . $examples1[$cmd_path]; if (isset($examples2[$cmd_path])) { echo "\n charcoal " . $cmd_path . ' ' . $examples2[$cmd_path]; } } if (isset($descriptions[$cmd_path])) { echo "\n\nThis command " . $descriptions[$cmd_path]; } } else { echo "Command not found: {$cmd_path}"; } echo "\n"; return b(true); }
/** * process event * * @param Charcoal_IEventContext $context * * @return boolean|Charcoal_Boolean */ public function processEvent($context) { /** @var GenerateModelEvent $event */ $event = $context->getEvent(); // get event parameters $db_name = $event->getDatabase(); /** @var Charcoal_SmartGateway $gw */ $gw = $context->getComponent('smart_gateway@:charcoal:db'); // find models in project/app path $find_path = Charcoal_EnumFindPath::FIND_PATH_PROJECT | Charcoal_EnumFindPath::FIND_PATH_APPLICATION; $models = $gw->listModels($find_path); // switch database $gw->selectDatabase($db_name); // create tables foreach ($models as $model_name => $model) { $table = $model->getTableName(); echo "creating table: [TABLE NAME]{$table} [MODEL NAME]{$model_name}\n"; $rows_affected = $gw->createTable(null, $model_name, true); if ($rows_affected) { echo "successfully created table[{$table}].\n"; } else { echo "failed to create table[{$table}].\n"; } } return b(true); }
/** * process event * * @param Charcoal_IEventContext $context event context * * @return Charcoal_Boolean|bool */ public function processEvent($context) { // $request = $context->getRequest(); // $response = $context->getResponse(); // $sequence = $context->getSequence(); // $procedure = $context->getProcedure(); $event = $context->getEvent(); if ($event instanceof Charcoal_TestResultEvent) { /** @var Charcoal_TestResultEvent $event */ $section = $event->getSection(); $action = $event->getAction(); $result = $event->getSuccess(); $this->assertions++; if (!$result) { $this->failures++; } if (!isset($this->section_map[$section])) { $this->section_map[$section] = array(array(), 0, 0); } list($tests, $assertions, $failures) = $this->section_map[$section]; $assertions++; if (!$result) { $failures++; } if (!in_array($action, $tests)) { $tests[] = $action; $this->tests++; } $this->section_map[$section] = array($tests, $assertions, $failures); } else { if ($event instanceof Charcoal_TestSummaryEvent) { if (!$context->getEventQueue()->isEmpty()) { // 他にイベントが残っている場合は処理しない return FALSE; } echo PHP_EOL; echo "==========================================" . PHP_EOL; echo "Test Result Summary" . PHP_EOL; echo " --------------------------------------- " . PHP_EOL; echo " Tests/Assertions/Failures by section:" . PHP_EOL . PHP_EOL; foreach ($this->section_map as $section => $map) { list($tests, $assertions, $failures) = $map; echo " [{$section}] " . count($tests) . " / {$assertions} / {$failures}" . PHP_EOL; } echo " --------------------------------------- " . PHP_EOL; echo " Total:" . PHP_EOL . PHP_EOL; echo " Tests: " . $this->tests . PHP_EOL; echo " Assertions: " . $this->assertions . PHP_EOL; echo " Failures: " . $this->failures . PHP_EOL; echo "==========================================" . PHP_EOL; } } return TRUE; }
/** * process event * * @param Charcoal_IEventContext $context * * @return boolean|Charcoal_Boolean */ public function processEvent($context) { /** @var GenerateModelEvent $event */ $event = $context->getEvent(); // get event parameters $db_name = $event->getDatabase(); $table_name = $event->getTable(); $out_dir = $event->getTargetDir(); $entity = Charcoal_System::pascalCase($table_name); $config_key = Charcoal_System::snakeCase($table_name); $table_model_class_name = "{$entity}TableModel"; $table_dto_class_name = "{$entity}TableDTO"; $listing_dto_class_name = "{$entity}ListingDTO"; /** @var Charcoal_SmartGateway $gw */ $gw = $context->getComponent('smart_gateway@:charcoal:db'); //======================================= // Mmake output directory //======================================= $out_dir = $this->prepareOutputDirectory($out_dir); //======================================= // confirm if the table exists //======================================= $sql = "SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? "; $params = array($table_name, $db_name); $count = $gw->queryValue(NULL, $sql, $params); if ($count < 1) { print "[ERROR] Specified table '{$table_name}' does not exist in schema: '{$db_name}'. Please check your database settings." . PHP_EOL; return b(true); } //======================================= // Retrieve column information //======================================= $sql = "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT, EXTRA, COLUMN_COMMENT "; $sql .= " FROM information_schema.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? "; $params = array($table_name, $db_name); $colmn_attr_list = $gw->query(NULL, $sql, $params); //======================================= // Genarate table model file //======================================= $this->generateTableModelFile($table_name, $colmn_attr_list, $table_model_class_name, $table_dto_class_name, $out_dir); //======================================= // Genarate table DTO file //======================================= $this->generateTableDtolFile($table_name, $colmn_attr_list, $table_dto_class_name, $out_dir); //======================================= // Genarate listing DTO file //======================================= $this->generateListingDtolFile($table_name, $colmn_attr_list, $listing_dto_class_name, $out_dir); //======================================= // Genarate config file //======================================= $this->generateTableConfigFile($table_name, $table_model_class_name, $config_key, $out_dir); return b(true); }
/** * execute tests * * @param string $action * @param Charcoal_IEventContext $context * * @return boolean */ public function test($action, $context) { $action = us($action); // file system component /** @var Charcoal_FileSystemComponent $fs */ $fs = $context->getComponent('file_system@:charcoal:file'); switch ($action) { case "create_dir": $dir = $fs->createDirectory("hoge", "707"); echo "created dir: {$dir}" . PHP_EOL; return TRUE; case "create_file": $file = $fs->createFile("test.txt", "Hello, File System!"); echo "created file: {$file}" . PHP_EOL; return TRUE; } return FALSE; }
/** * process event * * @param Charcoal_IEventContext $context event context * * @return boolean|Charcoal_Boolean * * @throws DivisionByZeroException */ public function processEvent($context) { $request = $context->getRequest(); // Get parameter from request $a = $request->getInteger('a', 0); $b = $request->getInteger('b', 0); $op = $request->getString('op', '+'); $a = ui($a); $b = ui($b); $op = us($op); $result = NULL; switch ($op) { case 'add': $result = $a + $b; break; case 'sub': $result = $a - $b; break; case 'mul': $result = $a * $b; break; case 'div': if ($b == 0) { throw new DivisionByZeroException(); } $result = $a / $b; break; } // show message if ($result) { echo "result:" . $result . eol(); } else { echo "<pre>USAGE:" . PHP_EOL; echo "http://" . $_SERVER['SERVER_NAME'] . "/calc/value1/value2/[add/sub/mul/div]" . PHP_EOL; echo "value1, value2: number" . eol(); echo "add: shows result of 'value1 + value2'" . PHP_EOL; echo "sub: shows result of 'value1 - value2'" . PHP_EOL; echo "mul: shows result of 'value1 * value2'" . PHP_EOL; echo "div: shows result of 'value1 / value2'" . PHP_EOL; echo "</pre>" . eol(); } // return TRUE if processing the procedure success. return TRUE; }
/** * process event * * @param Charcoal_IEventContext $context event context * * @return boolean */ public function processEvent($context) { $request = $context->getRequest(); // $response = $context->getResponse(); // $sequence = $context->getSequence(); // $procedure = $context->getProcedure(); // get paramter from command line $target_module = $request->getString('p1'); if (strlen($target_module) === 0) { echo 'target_module is needed.' . PHP_EOL; echo 'charcoal [target_module] [param1] [param2]...' . PHP_EOL; return TRUE; } $context->loadModule($target_module); // create shell_command event and push it into the event queue /** @var Charcoal_IEvent $event */ $event = $context->createEvent('shell_command'); $context->pushEvent($event); return b(true); }
/** * イベントを処理する * * @param Charcoal_IEventContext $context * * @return boolean */ public function processEvent($context) { $request = $context->getRequest(); // パラメータを取得 $database = us($request->getString('p2')); $table = us($request->getString('p3')); $out_dir = us($request->getString('p4')); //======================================= // Confirm input parameters //======================================= if (!empty($database) && !preg_match('/^[0-9a-zA-Z_\\-]*$/', $database)) { print "Parameter 2(database name) is wrong: {$database}" . PHP_EOL; return b(true); } if (!empty($table) && !preg_match('/^[0-9a-zA-Z_\\-]*$/', $table)) { print "Parameter 3(table name) is wrong: {$table}" . PHP_EOL; return b(true); } if (!empty($table) && !preg_match('/^[0-9a-zA-Z_\\-]*$/', $table)) { print "Parameter 4(output directory path) is wrong: {$out_dir}" . PHP_EOL; return b(true); } //======================================= // output directory //======================================= if (empty($out_dir)) { $out_dir = getcwd() ? getcwd() : Charcoal_ResourceLocator::getFrameworkPath('tmp'); } //======================================= // Send new project event //======================================= /** @var Charcoal_IEvent $event */ $event_path = 'generate_model_event@:charcoal:db:generate:model'; $event = $context->createEvent($event_path, array($database, $table, $out_dir)); $context->pushEvent($event); return b(true); }
/** * Process events * * @param Charcoal_IEventContext $context event context */ public function processEvent($context) { $request = $context->getRequest(); $response = $context->getResponse(); $sequence = $context->getSequence(); $procedure = $context->getProcedure(); $event = $context->getEvent(); // form token component $form_token = $context->getComponent(s('form_token@:charcoal:form')); if ($event instanceof Charcoal_SetupEvent) { $form_token->setupForm($sequence, $response); return b(TRUE); } elseif ($event instanceof Charcoal_AuthTokenEvent) { return $form_token->checkToken($sequence, $request); } return b(FALSE); }
/** * 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); }
/** * テスト * * @param string $action * @param Charcoal_IEventContext $context * * @return boolean */ public function test($action, $context) { $action = us($action); /** @var Charcoal_SmartGateway $gw */ $gw = $context->getComponent('smart_gateway@:charcoal:db'); $gw->reset(); switch ($action) { case "commit": // トランザクション開始 $gw->beginTrans(); $gw->autoCommit(FALSE); // 初期データの確認 $result = $gw->query(NULL, "SELECT * FROM posts WHERE post_id=1"); $this->assertEquals('stk2k', $result[0]['post_user'], true); // 更新 $gw->execute(NULL, "UPDATE posts set post_user = '******' where post_id = 1"); // コミット $gw->commitTrans(); // 検索 $result = $gw->query(NULL, "SELECT * FROM posts WHERE post_id=1"); $this->assertEquals('hoge', $result[0]['post_user']); return TRUE; case "query": $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query("query #1", $sql); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(1, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "select": $where = "blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("select #1", 'blogs', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(1, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "select_alias": $where = "b.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("select_alias #1", 'blogs as b', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(1, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "select_alias_forupdate": $where = "blog_name like ?"; $criteria = new Charcoal_SQLCriteria($where, array("My First Blog")); $result = $gw->findAllForUpdate("select_alias_forupdate #1", 'blogs as b', $criteria); foreach ($result as $row) { print print_r($row, true) . PHP_EOL; } return TRUE; case "inner_join": $where = "blogs.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("inner_join #1", 'blogs + posts on "blogs.blog_id = posts.blog_id" + comments on "posts.post_id = comments.post_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(3, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "left_join": $where = "blogs.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("left_join #1", 'blogs (+ posts on "blogs.blog_id = posts.blog_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(2, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "right_join": $where = "blogs.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("right_join #1", 'blogs +) posts on "blogs.blog_id = posts.blog_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } // 評価 $this->assertEquals(2, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "inner_join_alias": $where = "b.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("inner_join_alias #1", 'blogs as b + posts as p on "b.blog_id = p.blog_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(2, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "inner_join_multi": $where = "blogs.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("inner_join_multi #1", 'blogs + posts on "blogs.blog_id = posts.blog_id" + comments on "posts.post_id = comments.post_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(3, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "inner_join_multi_alias": $where = "b.blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array(1)); $result = $gw->findAll("inner_join_multi_alias #1", 'blogs as b + posts as p on "b.blog_id = p.blog_id" + comments as c on "p.post_id = c.post_id"', $criteria); $blog_name = ''; foreach ($result as $row) { $blog_name = $row['blog_name']; echo "blog_name:{$blog_name}" . eol(); } $this->assertEquals(3, count($result)); $this->assertEquals("my blog", $blog_name); return TRUE; case "count": $criteria = new Charcoal_SQLCriteria(); $result = $gw->count("count #1", 'posts', $criteria, '*'); echo "result:" . $result . eol(); // 評価 $this->assertEquals(3, $result); return TRUE; case "max": $criteria = new Charcoal_SQLCriteria(); $result = $gw->max("max #1", 'posts', $criteria, 'favorite'); echo "result:" . $result . eol(); $this->assertEquals(11, $result); return TRUE; case "min": $criteria = new Charcoal_SQLCriteria(); $result = $gw->min("min #1", 'posts', $criteria, 'favorite'); echo "result:" . $result . eol(); // 評価 $this->assertEquals(5, $result); return TRUE; case "avg": $criteria = new Charcoal_SQLCriteria(); $result = $gw->avg("avg #1", 'posts', $criteria, 'favorite'); echo "result:" . $result . eol(); $this->assertEquals(8, $result); return TRUE; case "count_alias": $criteria = new Charcoal_SQLCriteria(); $result = $gw->count("count_alias #1", 'posts as p', $criteria, '*'); echo "result:" . $result . eol(); $this->assertEquals(3, $result); return TRUE; case "max_alias": $criteria = new Charcoal_SQLCriteria(); $result = $gw->max("max_alias #1", 'posts as p + comments as c on "p.post_id = c.post_id"', $criteria, 'favorite'); echo "result:" . $result . eol(); $this->assertEquals(11, $result); return TRUE; case "find_first": $criteria = new Charcoal_SQLCriteria(); $criteria->setOrderBy('favorite'); $result = $gw->findFirst("find_first #1", 'posts', $criteria); echo "result:" . $result['post_title'] . eol(); $this->assertEquals('How does it work?', $result['post_title']); return TRUE; case "find_by_id": $result = $gw->findAll("find_by_id #1", 'posts', new Charcoal_SQLCriteria()); foreach ($result as $row) { $blog_id = $row['blog_id']; $blog = $gw->findById("find_by_id #2", 'blogs', $blog_id); $this->assertEquals($this->blog_name_expected[$blog_id], $blog['blog_name']); $blog_category_id = $blog['blog_category_id']; $category = $gw->findById("find_by_id #3", 'blog_category', $blog_category_id); $this->assertEquals($this->category_name_expected[$blog_category_id], $category['blog_category_name']); } return TRUE; case "save": // save by INSERT $dto = new PostTableDTO(); $dto->post_title = 'New Post'; $dto->post_body = 'New Post Body'; $dto->post_user = '******'; $count = $gw->count(NULL, 'posts', new Charcoal_SQLCriteria(), NULL); //echo $gw->popSQLHistory() . PHP_EOL; //echo "count(before save):" . $count . eol(); $this->assertEquals(3, $count); $new_id = $gw->save(NULL, "posts", $dto); //echo $gw->popSQLHistory() . PHP_EOL; $criteria = new Charcoal_SQLCriteria(); $criteria->setWhere("post_id = ?"); $criteria->setParams(array($new_id)); $new_record = $gw->findFirst(NULL, 'posts', $criteria); //echo $gw->popSQLHistory() . PHP_EOL; $count = $gw->count(NULL, 'posts', new Charcoal_SQLCriteria()); //echo $gw->popSQLHistory() . PHP_EOL; //echo "count(after save):" . $count . eol(); $this->assertEquals(4, $count); $this->assertEquals(4, $new_record['post_id']); $this->assertEquals('New Post', $new_record['post_title']); $this->assertEquals('New Post Body', $new_record['post_body']); $this->assertEquals('Ichiro', $new_record['post_user']); // save by UPDATE $dto->post_id = $new_id; $dto->post_date = array('function', 'now'); $dto->post_user = array('value', 'null'); $dto->post_body = array(1, 2, "apple", array('name' => 'stk2k'), array('sex' => 'male')); $time_before_update = time(); sleep(1); $gw->save(NULL, "posts", $dto); sleep(1); $time_after_update = time(); $criteria = new Charcoal_SQLCriteria(); $criteria->setWhere("post_id = ?"); $criteria->setParams(array($dto->post_id)); $the_record = $gw->findFirst(NULL, 'posts', $criteria); // check post date $this->assertGreaterThan($time_before_update, strtotime($the_record['post_date'])); $this->assertLessThan($time_after_update, strtotime($the_record['post_date'])); // check post user $this->assertEquals(NULL, $the_record['post_user']); // check post body(JSON) $post_body = json_decode($the_record['post_body'], true); $expeced = array(1, 2, "apple", array('name' => 'stk2k'), array('sex' => 'male')); $this->assertEquals($expeced, $post_body); return TRUE; case "fluent_api": $gw->select("b.blog_name, b.post_total, p.post_user, p.post_title")->from(s("blogs"), s("b"))->leftJoin(s("posts"), s("p"))->on("b.blog_id = p.blog_id")->where()->gt(s("b.post_total"), i(1))->orderBy(s("b.post_total DESC"))->limit(i(5))->offset(i(0))->prepareExecute()->findFirst("fluent_api #1")->result(); echo $gw->popSQLHistory() . PHP_EOL; // echo print_r($rs,true) . eol(); // echo "last SQL:" . $gw->getLastSQL() . eol(); // echo "last params:" . $gw->getLastParams() . eol(); return TRUE; case "recordset_query": $rsfactory1 = $gw->createRecordsetFactory(); // fetch mode: FETCHMODE_BOTH $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_query #1", $sql, NULL, $rsfactory1, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row['blog_id']], $row['blog_name']); } $rsfactory2 = $gw->createRecordsetFactory(Charcoal_IRecordset::FETCHMODE_ASSOC); $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_query #2", $sql, NULL, $rsfactory2, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row['blog_id']], $row['blog_name']); } $rsfactory3 = $gw->createRecordsetFactory(Charcoal_IRecordset::FETCHMODE_NUM); $sql = "SELECT blog_id, blog_name, post_total FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_query #3", $sql, NULL, $rsfactory3, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row[0]], $row[1]); } return TRUE; case "recordset_find": $rsfactory1 = $gw->createRecordsetFactory(); // fetch mode: FETCHMODE_ASSOC $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_find #1", $sql, NULL, $rsfactory1, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row['blog_id']], $row['blog_name']); } $rsfactory2 = $gw->createRecordsetFactory(Charcoal_IRecordset::FETCHMODE_ASSOC); $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_find #2", $sql, NULL, $rsfactory2, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row['blog_id']], $row['blog_name']); } $rsfactory3 = $gw->createRecordsetFactory(Charcoal_IRecordset::FETCHMODE_NUM); $sql = "SELECT blog_id, blog_name, post_total FROM blogs WHERE blog_id = 1"; $result = $gw->query("recordset_find #3", $sql, NULL, $rsfactory3, NULL); echo $gw->popSQLHistory() . PHP_EOL; foreach ($result as $row) { $this->assertEquals($this->blog_name_expected[$row[0]], $row[1]); } return TRUE; case "nested_recordset_query": $rsfactory1 = $gw->createRecordsetFactory(); // fetch mode: FETCHMODE_BOTH $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query(NULL, $sql, NULL, $rsfactory1); foreach ($result as $row) { $this->assertEquals(1, $row['blog_id']); $this->assertEquals($this->blog_name_expected[1], $row['blog_name']); $blog_category_id = $row['blog_category_id']; $sql = "SELECT * FROM blog_category WHERE blog_category_id = ?"; $result2 = $gw->query(NULL, $sql, array($blog_category_id), $rsfactory1); foreach ($result2 as $row2) { $this->assertEquals($blog_category_id, $row2['blog_category_id']); $this->assertEquals($this->category_name_expected[$blog_category_id], $row2['blog_category_name']); } } /* $rsfactory2 = $gw->createRecordsetFactory( Charcoal_IRecordset::FETCHMODE_ASSOC ); $sql = "SELECT * FROM blogs WHERE blog_id = 1"; $result = $gw->query( $sql, NULL, $rsfactory2 ); foreach( $result as $row ){ $this->assertEquals( 1, $row['blog_id'] ); $this->assertEquals( $this->blog_name_expected[1], $row['blog_name'] ); $blog_category_id = $row['blog_category_id']; $sql = "SELECT * FROM blog_category WHERE blog_category_id = ?"; $result2 = $gw->query( $sql, array($blog_category_id), $rsfactory2 ); foreach( $result2 as $row ){ $this->assertEquals( $blog_category_id, $row['blog_category_id'] ); $this->assertEquals( $this->category_name_expected[$blog_category_id], $row['blog_category_name'] ); } } $rsfactory3 = $gw->createRecordsetFactory( Charcoal_IRecordset::FETCHMODE_NUM ); $sql = "SELECT blog_id, blog_name, post_total, blog_category_id FROM blogs WHERE blog_id = 1"; $result = $gw->query( $sql, NULL, $rsfactory3 ); foreach( $result as $row ){ $this->assertEquals( 1, $row[0] ); $this->assertEquals( $this->blog_name_expected[1], $row[1] ); $blog_category_id = $row[3]; $sql = "SELECT blog_category_id, blog_category_name FROM blog_category WHERE blog_category_id = ?"; $result2 = $gw->query( $sql, array($blog_category_id), $rsfactory3 ); foreach( $result2 as $row ){ $this->assertEquals( $blog_category_id, $row[0] ); $this->assertEquals( $this->category_name_expected[$blog_category_id], $row[1] ); } } */ $another_ds = $context->createObject('PDO', 'data_source'); $default_ds_config = $gw->getDataSource()->getConfig(); //ad($default_ds_config); $config = $context->createConfig($default_ds_config->getAll()); $GLOBALS['hoge'] = true; ad($config); $config->set('token_key', 'foo'); $another_ds->configure($config); return TRUE; case "nested_recordset_find": return TRUE; case "delete_by_id": $gw->deleteById("delete_by_id #1", 'blog_category', 1); echo $gw->popSQLHistory() . PHP_EOL; $criteria = new Charcoal_SQLCriteria(''); $cnt = $gw->count("delete_by_id #2", 'blog_category', $criteria); echo 'cnt:' . $cnt . PHP_EOL; echo $gw->popSQLHistory() . PHP_EOL; return TRUE; case "delete_by_ids": $gw->deleteByIds("delete_by_ids #1", 'blog_category', array(1, 3)); echo $gw->popSQLHistory() . PHP_EOL; $criteria = new Charcoal_SQLCriteria(''); $cnt = $gw->count("delete_by_ids #2", 'blog_category', $criteria); echo 'cnt:' . $cnt . PHP_EOL; echo $gw->popSQLHistory() . PHP_EOL; return TRUE; /* ------------------------------ increment/decrement test */ /* ------------------------------ increment/decrement test */ case "increment_field": // increment post_toal by 1 $gw->incrementField("increment_field #1", 'blogs', 1, 'post_total'); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 2 => 3 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(3, $post_total); // increment post_toal by 2 $gw->incrementField("increment_field #1", 'blogs', 1, 'post_total', 2); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 3 => 5 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(5, $post_total); // increment post_toal by -5 $gw->incrementField("increment_field #1", 'blogs', 1, 'post_total', -5); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 5 => 0 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(0, $post_total); return TRUE; case "increment_field_by": // increment post_toal by 1 $gw->incrementFieldBy("increment_field_by #1", 'blogs', 'post_total', 'blog_name', 'my blog'); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 2 => 3 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(3, $post_total); // increment post_toal by 2 $gw->incrementFieldBy("increment_field_by #2", 'blogs', 'post_total', 'blog_name', 'my blog', 2); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 3 => 5 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(5, $post_total); // increment post_toal by -5 $gw->incrementFieldBy("increment_field_by #3", 'blogs', 'post_total', 'blog_name', 'my blog', -5); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 5 => 0 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(0, $post_total); return TRUE; case "decrement_field": // decrement post_toal by 1 $gw->decrementField("decrement_field #1", 'blogs', 1, 'post_total'); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 2 => 1 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(1, $post_total); // decrement post_toal by 2 $gw->decrementField("decrement_field #2", 'blogs', 1, 'post_total', 2); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 1 => -1 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); var_dump($post_total); $this->assertEquals(-1, $post_total); // decrement post_toal by -5 $gw->decrementField("decrement_field #3", 'blogs', 1, 'post_total', -5); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be -1 => 4 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(4, $post_total); return TRUE; case "decrement_field_by": // decrement post_toal by 1 $gw->decrementFieldBy("decrement_field_by #1", 'blogs', 'post_total', 'blog_name', 'my blog'); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 2 => 1 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(1, $post_total); // decrement post_toal by 2 $gw->decrementFieldBy("decrement_field_by #2", 'blogs', 'post_total', 'blog_name', 'my blog', 2); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be 1 => -1 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //ar_dump($post_total); $this->assertEquals(-1, $post_total); // decrement post_toal by -5 $gw->decrementFieldBy("decrement_field_by #3", 'blogs', 'post_total', 'blog_name', 'my blog', -5); //echo $gw->popSQLHistory() . PHP_EOL; // post_total must be -1 => 4 $pdo = new DuplicatedPdo($gw); $post_total = $pdo->queryValue("SELECT post_total FROM blogs WHERE blog_id = ?", [1]); //var_dump($post_total); $this->assertEquals(4, $post_total); return TRUE; /* ------------------------------ insert test */ /* ------------------------------ insert test */ case "insert": // INSERT $blog = new BlogTableDTO(); $blog->blog_name = 'my new blog'; $blog->post_total = 123; $blog->created_date = array('function', 'now'); $blog->modified_date = array('function', 'now'); $time_insert_before = time(); sleep(1); $gw->insert(NULL, 'blogs', $blog); sleep(1); $time_insert_after = time(); $blog_id = $gw->getLastInsertId(); $this->assertEquals(3, $blog_id); // INSERTの確認 $where = "blog_id = ?"; $criteria = new Charcoal_SQLCriteria($where, array($blog_id)); $blog = $gw->findFirst("insert #1", 'blogs', $criteria); $this->assertEquals(3, $blog['blog_id']); $this->assertEquals('my new blog', $blog['blog_name']); $this->assertEquals(123, $blog['post_total']); $this->assertGreaterThan($time_insert_before, strtotime($blog['created_date'])); $this->assertLessThan($time_insert_after, strtotime($blog['created_date'])); return TRUE; case "bulk_insert": // BULK INSERT $blogs = array(); $blog = new BlogTableDTO(); $blog->blog_name = 'my new blog'; $blog->post_total = 123; $blog->created_date = array('function', 'now'); $blog->modified_date = array('function', 'now'); $blogs[] = $blog; $blog = new BlogTableDTO(); $blog->blog_name = 'my new blog2'; $blog->post_total = 44; $blog->created_date = array('function', 'now'); $blog->modified_date = array('function', 'now'); $blogs[] = $blog; $time_insert_before = time(); sleep(1); $inserted_rows = $gw->insertAll(NULL, 'blogs', $blogs); $this->assertEquals(2, $inserted_rows); sleep(1); $time_insert_after = time(); // INSERTの確認 $where = "blog_name like 'my new blog%'"; $criteria = new Charcoal_SQLCriteria($where, NULL, 'blog_id'); $result = $gw->findAll(NULL, 'blogs', $criteria); $blog = array_shift($result); $this->assertEquals(3, $blog['blog_id']); $this->assertEquals('my new blog', $blog['blog_name']); $this->assertEquals(123, $blog['post_total']); $this->assertGreaterThan($time_insert_before, strtotime($blog['created_date'])); $this->assertLessThan($time_insert_after, strtotime($blog['created_date'])); $blog = array_shift($result); $this->assertEquals(4, $blog['blog_id']); $this->assertEquals('my new blog2', $blog['blog_name']); $this->assertEquals(44, $blog['post_total']); $this->assertGreaterThan($time_insert_before, strtotime($blog['created_date'])); $this->assertLessThan($time_insert_after, strtotime($blog['created_date'])); return TRUE; /* ------------------------------ update test */ /* ------------------------------ update test */ case "update_field": echo "selected database:" . $gw->getSelectedDatabase() . PHP_EOL; // update a field $gw->updateField('update_field #1', 'blogs', 1, 'post_total', 5); echo $gw->popSQLHistory() . PHP_EOL; // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals('my blog', $row['blog_name']); $this->assertEquals(5, $row['post_total']); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(1, $row['post_total']); break; } } return TRUE; case "update_fields": // update fields $fields = array('post_total' => 999, 'blog_name' => 'super popular blog'); $gw->updateFields('update_fields #1', 'blogs', 1, $fields); echo $gw->popSQLHistory() . PHP_EOL; // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals('super popular blog', $row['blog_name']); $this->assertEquals(999, $row['post_total']); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(1, $row['post_total']); break; } } return TRUE; case "update_field_by": // update fields in a row $rows = $gw->updateFieldBy('update_field_by #1', 'blogs', 'blog_name', 'another blog', 'blog_id', 1); echo $gw->popSQLHistory() . PHP_EOL; $this->assertEquals(1, $rows); // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(2, $row['post_total']); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(1, $row['post_total']); break; } } // update fields in multiple rows $rows = $gw->updateFieldBy('update_field_by #1', 'blogs', 'post_total', 3, 'blog_name', 'another blog'); echo $gw->popSQLHistory() . PHP_EOL; $this->assertEquals(2, $rows); // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(3, $row['post_total']); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(3, $row['post_total']); break; } } return TRUE; case "update_field_now": $start_time = time(); // update field to current time $gw->updateFieldNow('update_field_now #1', 'blogs', 1, 'modified_date'); echo $gw->popSQLHistory() . PHP_EOL; // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals('my blog', $row['blog_name']); $this->assertEquals(2, $row['post_total']); $this->assertEquals('2010-01-02 12:56:12', $row['created_date']); $this->assertLessThanOrEqual($start_time, strtotime($row['modified_date'])); $this->assertGreaterThanOrEqual(time(), strtotime($row['modified_date'])); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(1, $row['post_total']); $this->assertEquals('2010-01-12 02:12:32', $row['created_date']); $this->assertEquals('2010-01-15 11:42:02', $row['modified_date']); break; } } return TRUE; case "update_field_null": // update fields in a row $gw->updateFieldNull('update_field_null #1', 'blogs', 1, 'blog_name'); echo $gw->popSQLHistory() . PHP_EOL; // confirm result $pdo = new DuplicatedPdo($gw); $rows = $pdo->queryRows("SELECT * FROM blogs"); //var_dump($rows); foreach ($rows as $row) { switch ($row['blog_id']) { case 1: $this->assertEquals(1, $row['blog_category_id']); $this->assertEquals(null, $row['blog_name']); $this->assertEquals(2, $row['post_total']); break; case 2: $this->assertEquals(2, $row['blog_category_id']); $this->assertEquals('another blog', $row['blog_name']); $this->assertEquals(1, $row['post_total']); break; } } return TRUE; /* ------------------------------ select db test */ /* ------------------------------ select db test */ case "select_db": echo "selected database:" . $gw->getSelectedDatabase() . PHP_EOL; $exists = $gw->existsTable('item'); $this->assertEquals(true, $exists); $exists = $gw->existsTable('item2'); $this->assertEquals(false, $exists); $gw->selectDatabase('test2'); echo "selected database:" . $gw->getSelectedDatabase() . PHP_EOL; $exists = $gw->existsTable('item'); $this->assertEquals(false, $exists); $exists = $gw->existsTable('item2'); $this->assertEquals(true, $exists); return TRUE; /* ------------------------------ list models test */ /* ------------------------------ list models test */ case "list_models_all": $models = $gw->listModels(); $this->assertEquals(7, count($models)); $bundled_models = array('Charcoal_SessionTableModel', 'BlogCategoryTableModel', 'BlogTableModel', 'CommentTableModel', 'ItemTableModel', 'Item2TableModel', 'PostTableModel', 'TestTableModel'); foreach ($models as $model) { $this->assertTrue($model instanceof Charcoal_ITableModel); $clazz = get_class($model); echo $clazz . PHP_EOL; $this->assertTrue(in_array($clazz, $bundled_models)); } return TRUE; case "list_models_framework": $models = $gw->listModels(Charcoal_EnumFindPath::FIND_PATH_FRAMEWORK); $this->assertEquals(1, count($models)); $bundled_models = array('Charcoal_SessionTableModel'); foreach ($models as $model) { $this->assertTrue($model instanceof Charcoal_ITableModel); $clazz = get_class($model); echo $clazz . PHP_EOL; $this->assertTrue(in_array($clazz, $bundled_models)); } return TRUE; case "list_models_project": $models = $gw->listModels(Charcoal_EnumFindPath::FIND_PATH_PROJECT); $this->assertEquals(6, count($models)); $bundled_models = array('BlogCategoryTableModel', 'BlogTableModel', 'CommentTableModel', 'ItemTableModel', 'Item2TableModel', 'PostTableModel', 'TestTableModel'); foreach ($models as $model) { $this->assertTrue($model instanceof Charcoal_ITableModel); $clazz = get_class($model); echo $clazz . PHP_EOL; $this->assertTrue(in_array($clazz, $bundled_models)); } return TRUE; case "list_models_application": $models = $gw->listModels(Charcoal_EnumFindPath::FIND_PATH_APPLICATION); $this->assertEquals(0, count($models)); return TRUE; default: break; } return FALSE; }
/** * execute tests * * @param string $action * @param Charcoal_IEventContext $context * * @return boolean */ public function test($action, $context) { $action = us($action); /** @var Charcoal_SmartGateway $gw */ $gw = $context->getComponent('smart_gateway@:charcoal:db'); switch ($action) { case "dml_truncate": $rows = $this->countTableRows('test'); $this->assertEquals(1, $rows); $gw->truncateTable(__FILE__ . '(' . __LINE__ . ')', 'test'); $rows = $this->countTableRows('test'); $this->assertEquals(0, $rows); return TRUE; case "dml_bulk_insert": // テーブルの行数は1になっているはず $this->assertEquals(1, $this->countTableRows('test')); // appleの行数は0になっているはず $this->assertEquals(0, $this->countRows('test', 'name = "apple"')); // grapeの行数は0になっているはず $this->assertEquals(0, $this->countRows('test', 'name = "grape"')); // orageの行数は0になっているはず $this->assertEquals(0, $this->countRows('test', 'name = "orage"')); // melonの行数は0になっているはず $this->assertEquals(0, $this->countRows('test', 'name = "melon"')); // apple/grape/orage/melonのデータをバルクインサート $data_set = array(new Charcoal_DTO(['name' => 'apple', 'price' => 100]), new Charcoal_DTO(['name' => 'grape', 'price' => 200]), new Charcoal_DTO(['name' => 'orage', 'price' => 150]), new Charcoal_DTO(['name' => 'melon', 'price' => 1800])); $gw->insertAll(null, 'test', $data_set); // テーブルの行数は5になっているはず $this->assertEquals(5, $this->countTableRows('test')); // appleの行数は1になっているはず $this->assertEquals(1, $this->countRows('test', 'name = "apple"')); // grapeの行数は1になっているはず $this->assertEquals(1, $this->countRows('test', 'name = "grape"')); // orageの行数は1になっているはず $this->assertEquals(1, $this->countRows('test', 'name = "orage"')); // melonの行数は1になっているはず $this->assertEquals(1, $this->countRows('test', 'name = "melon"')); return TRUE; } return FALSE; }
/** * 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); }
/** * Process events * * @param Charcoal_IEventContext $context event context * * @return Charcoal_Boolean|bool */ public function processEvent($context) { $this->context = $context; /** @var Charcoal_TestEvent $event */ $event = $context->getEvent(); $is_debug = $context->isDebug(); // パラメータを取得 $section = $event->getSection(); $target = $event->getTarget(); $actions = $event->getActions(); $this->section = $section; if ($is_debug) { log_debug("debug,event", "event section: {$section}"); } if ($is_debug) { log_debug("debug,event", "event target: {$target}"); } if ($is_debug) { log_debug("debug,event", "event actions: {$actions}"); } if ($is_debug) { log_debug("debug,event", "this object path: " . $this->getObjectPath()); } if ($target != $this->getObjectPath()) { if ($is_debug) { log_debug("debug,event", "not target: " . $event); } return FALSE; } if ($is_debug) { log_debug("debug,event", "target: " . $event); } $actions = explode(',', $actions); // アクションに対するテストが記述されているか確認する $total_actions = 0; if ($actions) { foreach ($actions as $action) { $action = trim($action); if (strlen($action) === 0) { continue; } if ($this->isValidAction($action)) { $total_actions++; } } } if ($total_actions === 0) { return TRUE; } // テスト実行 $this->tests = 0; $this->asserts = 0; $this->failures = 0; echo PHP_EOL . "===================================================" . PHP_EOL; echo "Section[{$section}](total actions:{$total_actions})" . PHP_EOL . PHP_EOL; foreach ($actions as $action) { $action = trim($action); if (strlen($action) === 0) { continue; } $this->action = $action; if (!$this->isValidAction($action)) { continue; } //echo "-------------------------------------" . PHP_EOL; echo "Doing action: [{$action}] ..." . PHP_EOL; try { $this->setUp($action, $context); } catch (Exception $e) { echo "Test execution failed while setup:" . $e . PHP_EOL; return TRUE; } try { $tested = $this->test($action, $context); if ($tested) { $this->tests++; } } catch (Exception $e) { echo "[Info]Caught exception:" . get_class($e) . PHP_EOL; if ($this->expected_exception) { if ($this->expected_exception != get_class($e)) { $expected = $this->expected_exception; $actual = get_class($e); $this->message2(get_class($e), "Expected", "Actual", $expected, $actual); } } else { echo "[Warning]Test execution failed while test:" . $e . PHP_EOL; } } try { $this->cleanUp($action, $context); } catch (Exception $e) { echo "Test execution failed while clean up:" . $e . PHP_EOL; return TRUE; } echo "Action finished: [{$action}]" . PHP_EOL . PHP_EOL; } // 終了メッセージ if ($this->tests > 0) { echo "Tests complete! : [{$section}]" . PHP_EOL . PHP_EOL; echo "Tests: {$this->tests} Assertions: {$this->asserts} Failures: {$this->failures}" . PHP_EOL; } else { echo "No tests were processed." . PHP_EOL; } echo "===================================================" . PHP_EOL . PHP_EOL; return TRUE; }
/** * process event * * @param Charcoal_IEventContext $context * * @return boolean|Charcoal_Boolean */ public function processEvent($context) { /** @var ShowTableEvent $event */ $event = $context->getEvent(); // get event parameters $db_name = $event->getDatabase(); $table_name = $event->getTable(); /** @var Charcoal_SmartGateway $gw */ $gw = $context->getComponent('smart_gateway@:charcoal:db'); //======================================= // confirm if the table exists //======================================= $sql = "SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? "; $params = array($table_name, $db_name); $count = $gw->queryValue(NULL, $sql, $params); if ($count < 1) { print "[ERROR] Specified table '{$table_name}' does not exist in schema: '{$db_name}'. Maybe table name is wrong?" . PHP_EOL; return b(true); } print "Showing table information." . PHP_EOL . PHP_EOL; print "=========================================" . PHP_EOL; print "Table description: {$table_name}" . PHP_EOL . PHP_EOL; //======================================= // Retrieve column information //======================================= $sql = "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT, EXTRA, COLUMN_COMMENT "; $sql .= " FROM information_schema.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? "; $params = array($table_name, $db_name); $colmn_attr_list = $gw->query(NULL, $sql, $params); // get max length $field_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'COLUMN_NAME', 'Field Name'); $type_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'COLUMN_TYPE', 'Type'); $null_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'IS_NULLABLE', 'Null'); $key_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'COLUMN_KEY', 'Key'); $default_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'COLUMN_DEFAULT', 'Default'); $extra_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'EXTRA', 'Extra'); $comment_max_width = $this->getMaxLengthOfMeta($colmn_attr_list, 'COLUMN_COMMENT', 'Comment'); print "null_max_width: {$null_max_width}\n"; print "key_max_width: {$key_max_width}\n"; print str_pad("Field Name", $field_max_width + 1) . " "; print str_pad("Type", $type_max_width + 1) . " "; print str_pad("Null", $null_max_width + 1) . " "; print str_pad("Key", $key_max_width + 1) . " "; print str_pad("Default", $default_max_width + 1) . " "; print str_pad("Extra", $extra_max_width + 1) . " "; print str_pad("Comment", $comment_max_width + 1) . PHP_EOL; $line_width = $field_max_width + $type_max_width + $null_max_width + $key_max_width + $default_max_width + $extra_max_width + $comment_max_width + 15; print str_repeat("-", $line_width) . PHP_EOL; $conv = Charcoal_EncodingConverter::fromString($this->getSandbox(), 'DB', 'CLI'); foreach ($colmn_attr_list as $colmn_attr) { $field = $colmn_attr['COLUMN_NAME']; $type = $colmn_attr['COLUMN_TYPE']; $null = $colmn_attr['IS_NULLABLE']; $key = $colmn_attr['COLUMN_KEY']; $default = $colmn_attr['COLUMN_DEFAULT']; $extra = $colmn_attr['EXTRA']; $comment = $colmn_attr['COLUMN_COMMENT']; $comment = $conv->convert($comment); $field = str_pad($field, $field_max_width + 1); $type = str_pad($type, $type_max_width + 1); $null = str_pad($null, $null_max_width + 1); $key = str_pad($key, $key_max_width + 1); $default = str_pad($default, $default_max_width + 1); $extra = str_pad($extra, $extra_max_width + 1); $comment = str_pad($comment, $comment_max_width + 1); print "{$field} {$type} {$null} {$key} {$default} {$extra} {$comment}" . PHP_EOL; } print PHP_EOL . "Done." . PHP_EOL; return b(true); }
/** * 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; }
/** * process event * * @param Charcoal_IEventContext $context event context * * @return Charcoal_Boolean|bool */ public function processEvent($context) { $request = $context->getRequest(); // $response = $context->getResponse(); // $sequence = $context->getSequence(); // $procedure = $context->getProcedure(); echo PHP_EOL; echo "==========================================" . PHP_EOL; echo "CharcoalPHP Test Runner" . PHP_EOL; echo " Framework Version:" . Charcoal_Framework::getVersion() . PHP_EOL; echo "==========================================" . PHP_EOL; // get paramter from command line $scenario = $request->getString('scenario'); $scenario = trim($scenario); log_debug("debug,scenario", "scenario: {$scenario}"); if ($scenario === NULL) { echo "actions or scenario parameter must be specified." . PHP_EOL; log_error("debug,error,scenario", "actions or scenario parameter must be specified."); return TRUE; } $scenario_file = $this->scenario_dir . '/' . $scenario . '.scenario.ini'; if (!is_file($scenario_file)) { echo "scenario file not found: {$scenario_file}" . PHP_EOL; log_error("debug,error,scenario", "scenario file not found: {$scenario_file}"); return TRUE; } $scenario_data = parse_ini_file($scenario_file, TRUE); log_debug("debug,scenario", "scenario_data: " . print_r($scenario_data, true)); if (empty($scenario_data)) { echo "couldn't read scenario file: {$scenario_file}" . PHP_EOL; log_error("debug,error,scenario", "couldn't read scenario file: {$scenario_file}"); return TRUE; } foreach ($scenario_data as $section => $data) { $target = isset($data['target']) ? $data['target'] : NULL; $actions = isset($data['actions']) ? $data['actions'] : NULL; $enabled = isset($data['enabled']) ? $data['enabled'] : TRUE; log_debug("debug,scenario", "target: {$target}"); log_debug("debug,scenario", "actions: {$actions}"); log_debug("debug,scenario", "enabled: {$enabled}"); if (in_array(strtolower($enabled), array('0', 'false', 'no'))) { echo "section[{$section}] is DISABLED. will skip." . PHP_EOL; log_warning("debug, scenario", "section[{$section}] is DISABLED."); continue; } if (empty($target)) { echo "[WARNING] 'target' is not found at section[{$section}]" . PHP_EOL; log_warning("debug, scenario", "'target' is not found at section[{$section}]"); continue; } if (empty($actions)) { echo "[WARNING] 'actions' is not found at section[{$section}]" . PHP_EOL; log_warning("debug, scenario", "'actions' is not found at section[{$section}]"); continue; } $target_path = new Charcoal_ObjectPath($target); $module_path = '@' . $target_path->getVirtualPath(); $context->loadModule($module_path); log_info("debug,scenario", "loaded module: {$module_path}"); $event_args = array($section, $target, $actions); /** @var Charcoal_IEvent $event */ $event = $context->createEvent('test', $event_args); $context->pushEvent($event); log_debug("debug,scenario", "event_args: " . print_r($event_args, true)); log_debug("debug,scenario", "pushed event: " . print_r($event, true)); } // request fo test summary /** @var Charcoal_IEvent $event */ $event = $context->createEvent('test_summary'); $context->pushEvent($event); return TRUE; }