/** * Executes the cronjob task * * @param mixed $pid * @param mixed $md5 */ public static function execute($pid, $md5) { /** @var RenaApp $app */ $app = RenaApp::getInstance(); // Foreach page, throw the war url in question at the Resque task $data = json_decode($app->cURL->getData("https://public-crest.eveonline.com/wars/", 0), true); $pageCount = $data["pageCount"]; $currPage = 1; while ($currPage <= $pageCount) { // Get the data for the current page $data = json_decode($app->cURL->getData("https://public-crest.eveonline.com/wars/?page=" . $currPage, 0), true); foreach ($data["items"] as $war) { // Figure out if it's already inserted, and if it has ended (or has zero kills) $inserted = $app->wars->getWarByID($war["id"]); // If nothing is inserted we'll update if (empty($inserted)) { \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\populateWars", array("url" => $war["href"])); } $date = new DateTime("+36 hour"); $dateIn36Hours = $date->format("Y-m-d H:i:s"); if (!empty($inserted) && $inserted["lastUpdated"] > $dateIn36Hours) { \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\populateWars", array("url" => $war["href"])); } } // Increment the currentPage variable, so we can fetch the next set of wars $currPage++; } exit; // Keep this at the bottom, to make sure the fork exits }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena /** @var RenaApp $app */ $app = RenaApp::getInstance(); $app->StatsD->increment("ccpRequests"); $data = $app->EVEEVEAllianceList->getData(); if (isset($data["result"]["alliances"])) { foreach ($data["result"]["alliances"] as $alliance) { $output->writeln("Updating/Adding: " . $alliance["name"]); // Update all the corporations in the alliance.. maybe we missed one? foreach ($alliance["memberCorporations"] as $corporation) { \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\updateCorporation", array("corporationID" => $corporation["corporationID"])); } $allianceID = $alliance["allianceID"]; $allianceName = $alliance["name"]; $allianceTicker = $alliance["shortName"]; $memberCount = $alliance["memberCount"]; $executorCorporationID = $alliance["executorCorpID"]; $information = json_decode($app->cURL->getData("https://public-crest.eveonline.com/alliances/{$allianceID}/"), true)["description"]; $app->alliances->updateAllianceDetails($allianceID, $allianceName, $allianceTicker, $memberCount, $executorCorporationID, $information); $app->alliances->setLastUpdated($allianceID, date("Y-m-d H:i:s")); } } }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena /** @var RenaApp $app */ $app = RenaApp::getInstance(); $run = true; $oldKillID = 0; do { $p = \RedisQ\Action::listen("redisq.zkillboard.com"); if ($p["killID"] > $oldKillID) { // Get the killmail data. $k = $app->CrestFunctions->generateFromCREST($p); // Poke statsd $app->StatsD->increment("zKillboardReceived"); // Now lets make the json and hash $json = json_encode($k, JSON_NUMERIC_CHECK); $hash = $app->CrestFunctions->generateCRESTHash($k); //$hash = hash("sha256", ":" . $k["killTime"] . ":" . $k["solarSystemID"] . ":" . $k["moonID"] . "::" . $k["victim"]["characterID"] . ":" . $k["victim"]["shipTypeID"] . ":" . $k["victim"]["damageTaken"] . ":"); // Lets insert the killmail! $insert = $app->killmails->insertIntoKillmails($p["killID"], 0, $hash, "zkillboardRedisQ", $json); // Upgrade it if ($insert > 0) { \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $p["killID"])); } } $oldKillID = $p["killID"]; } while ($run == true); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena $app = RenaApp::getInstance(); $run = true; $oldKillID = 0; do { $p = \RedisQ\Action::listen("redisq.zkillboard.com"); if ($p["killID"] > $oldKillID) { // Get the killmail data. $k = $app->killmails->generateFromCREST($p); // Poke statsd $app->StatsD->increment("zKillboardReceived"); // Now lets make the json and hash $json = json_encode($k, JSON_NUMERIC_CHECK); $hash = hash("sha256", ":" . $k["killTime"] . ":" . $k["solarSystemID"] . ":" . $k["moonID"] . "::" . $k["victim"]["characterID"] . ":" . $k["victim"]["shipTypeID"] . ":" . $k["victim"]["damageTaken"] . ":"); // Push it over zmq to the websocket $context = new ZMQContext(); $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena"); $socket->connect("tcp://localhost:5555"); $socket->send($json); // Lets insert the killmail! $app->killmails->insertKillmail($p["killID"], 0, $hash, "zkillboardRedisQ", $json); } $oldKillID = $p["killID"]; } while ($run == true); }
/** * @param $pid * @param $md5 */ public static function execute($pid, $md5) { $app = RenaApp::getInstance(); if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) { return; } \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updateAlliances"); exit; }
/** * Executes the cronjob task * * @param mixed $pid * @param mixed $md5 * @internal param RenaApp $app */ public static function execute($pid, $md5) { /** @var RenaApp $app */ $app = RenaApp::getInstance(); $toUpgrade = $app->Db->query("SELECT killID FROM killmails WHERE upgraded = 0 AND processed != 1 ORDER BY dateAdded ASC LIMIT 100", array(), 1); if ($toUpgrade) { foreach ($toUpgrade as $kill) { \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $kill["killID"])); } } exit; // Keep this at the bottom, to make sure the fork exits }
/** * @param $pid * @param $md5 */ public static function execute($pid, $md5) { $app = RenaApp::getInstance(); if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) { return; } $toFetch = $app->Db->query("SELECT * FROM apiKeyCharacters WHERE cachedUntil < now() OR lastChecked < date_sub(now(), INTERVAL 24 HOUR) ORDER BY lastChecked LIMIT 500", array(), 1); if ($toFetch) { foreach ($toFetch as $apiFetches) { \Resque::enqueue("important", "\\ProjectRena\\Task\\Resque\\killMailFetcher", array("fetchData" => serialize($apiFetches))); } } exit; // Keep this at the bottom, to make sure the fork exits }
/** * @param InputInterface $input * @param OutputInterface $output * @return void * @throws Exception */ protected function execute(InputInterface $input, OutputInterface $output) { /** @var RenaApp $app */ $app = RenaApp::getInstance(); // Setup the url and cache path $url = "https://www.fuzzwork.co.uk/dump/"; $cache = __DIR__ . "/../../cache/update"; // Create the cache dir if it doesn't exist if (!file_exists($cache)) { mkdir($cache); } // Fetch the md5 $md5file = "mysql-latest.tar.bz2.md5"; $md5 = explode(" ", $app->cURL->getData($url . $md5file, 0))[0]; $lastSeenMD5 = $app->Storage->get("ccpdataMD5"); if ($lastSeenMD5 !== $md5 || !$input->getOption("force") === false) { $output->writeln("Updating to latest CCP data dump"); $dbFiles = array("dgmAttributeCategories", "dgmAttributeTypes", "dgmEffects", "dgmTypeAttributes", "dgmTypeEffects", "invFlags", "invGroups", "invTypes", "mapDenormalize", "mapRegions", "mapSolarSystems", "mapConstellations"); $type = ".sql.bz2"; foreach ($dbFiles as $file) { $output->writeln("Updating {$file}"); $dataURL = $url . "latest/" . $file . $type; try { file_put_contents("{$cache}/{$file}{$type}", $app->cURL->getData($dataURL, 0)); $sqlData = bzopen("{$cache}/{$file}{$type}", "r"); // Open the BZip data // Read the BZip data and append it to data $data = ""; while (!feof($sqlData)) { $data .= bzread($sqlData, 4096); } } catch (\Exception $e) { throw new \Exception($e->getMessage()); } // Since rena uses tokuDB, we'll replace InnoDB with TokuDB here, just because we can.. $data = str_replace("ENGINE=InnoDB", "ENGINE=TokuDB", $data); $dataParts = explode(";\n", $data); foreach ($dataParts as $qry) { $query = $qry . ";"; $app->Db->execute($query); } // Remove the stored BZip file from the drive - no need to store it.. unlink("{$cache}/{$file}.sql.bz2"); } $app->Storage->set("ccpdataMD5", $md5); } }
/** * @param $pid * @param $md5 */ public static function execute($pid, $md5) { $app = RenaApp::getInstance(); if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) { return; } $apiKeys = $app->Db->query("SELECT keyID, vCode FROM apiKeys WHERE lastValidation < date_sub(now(), INTERVAL 6 HOUR) ORDER BY lastValidation DESC LIMIT 500", array(), 0); if ($apiKeys) { foreach ($apiKeys as $api) { $keyID = $api["keyID"]; $vCode = $api["vCode"]; // Update the lastValidation to in ten minutes, just so we don't insert it again and again \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updateApiKeys", array("keyID" => $keyID, "vCode" => $vCode)); } } exit; }
/** * @param $pid * @param $md5 */ public static function execute($pid, $md5) { $app = RenaApp::getInstance(); if ($app->Storage->get("Api904") >= date("Y-m-d H:i:s")) { return; } $characters = $app->Db->query("SELECT characterID FROM characters WHERE lastUpdated < date_sub(now(), INTERVAL 7 DAY) AND characterID != 0 ORDER BY lastUpdated LIMIT 500", array(), 0); if ($characters) { foreach ($characters as $character) { // Get the characterID to update $characterID = $character["characterID"]; // Throw the ID after Resque which will update the characters information \Resque::enqueue("default", "\\ProjectRena\\Task\\Resque\\updateCharacter", array("characterID" => $characterID)); } } exit; }
/** * Executes the cronjob task * * @param mixed $pid * @param mixed $md5 */ public static function execute($pid, $md5) { $app = RenaApp::getInstance(); $typeIDs = $app->Db->query("SELECT typeID FROM invTypes WHERE published = 1 AND marketGroupID != 0"); $cnt = 0; $fetchIDs = array(); foreach ($typeIDs as $row) { $typeID = $row["typeID"]; $fetchIDs[] = $typeID; $cnt++; if ($cnt == 20) { \Resque::enqueue("now", "\\ProjectRena\\Task\\Resque\\updatePrices", array("typeIDs" => $fetchIDs)); $fetchIDs = array(); $cnt = 0; } } exit; // Keep this at the bottom, to make sure the fork exits }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $app = RenaApp::getInstance(); // Check if composer is in the dir if (!file_exists(__DIR__ . "/../../composer.phar")) { $output->writeln("Composer doesn't exist, downloading it"); $composer = $app->cURL->getData("https://getcomposer.org/composer.phar", 0); file_put_contents(__DIR__ . "/../../composer.phar", $composer); } $output->writeln("Updating composer"); exec("php " . __DIR__ . "/../../composer.phar update -o"); // Generate an optimized loader $output->writeln("Generating Optimized Loader"); $loaderCode = $this->generateOptimizedLoader($app); file_put_contents(__DIR__ . "/../OptimizedLoader.php", $loaderCode); // Update RenaApp $renaAppCode = $this->generateRenaApp(); $output->writeln("Generating RenaApp"); file_put_contents(__DIR__ . "/../RenaApp.php", $renaAppCode); // Do more stuff (Clear cache?) }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena $app = RenaApp::getInstance(); $startTime = time() + 3600; // Current time + 60 minutes $run = true; $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp")); $stomp->subscribe("/topic/kills", array("id" => "projectRena", "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); do { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); if (!empty($killdata)) { $app->StatsD->increment("stompReceived"); if (isset($killdata["_stringValue"])) { unset($killdata["_stringValue"]); } // Fix the killID $killdata["killID"] = (int) $killdata["killID"]; $json = json_encode($killdata, JSON_NUMERIC_CHECK); $hash = hash("sha256", ":" . $killdata["killTime"] . ":" . $killdata["solarSystemID"] . ":" . $killdata["moonID"] . "::" . $killdata["victim"]["characterID"] . ":" . $killdata["victim"]["shipTypeID"] . ":" . $killdata["victim"]["damageTaken"] . ":"); $inserted = $app->Db->execute("INSERT IGNORE INTO killmails (killID, hash, source, kill_json) VALUES (:killID, :hash, :source, :kill_json)", array(":killID" => $killdata["killID"], ":hash" => $hash, ":source" => "stomp", ":kill_json" => $json)); if ($inserted > 0) { // Push it over zmq to the websocket $context = new ZMQContext(); $socket = $context->getSocket(ZMQ::SOCKET_PUSH, "rena"); $socket->connect("tcp://localhost:5555"); $socket->send($json); } } $stomp->ack($frame->headers["message-id"]); } // Kill it after an hour if ($startTime <= time()) { $run = false; } } while ($run == true); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $app = RenaApp::getInstance(); // Setup the url and cache path $url = "https://www.fuzzwork.co.uk/dump/"; $cache = __DIR__ . "/../../cache/update"; // Create the cache dir if it doesn't exist if (!file_exists($cache)) { mkdir($cache); } // Fetch the md5 $md5file = "mysql-latest.tar.bz2.md5"; $md5 = explode(" ", $app->cURL->getData($url . $md5file, 0))[0]; $lastSeenMD5 = $app->Storage->get("ccpdataMD5"); if ($lastSeenMD5 != $md5) { $output->writeln("Updating to latest CCP data dump"); $dbFiles = array("dgmAttributeCategories", "dgmAttributeTypes", "dgmEffects", "dgmTypeAttributes", "dgmTypeEffects", "invFlags", "invGroups", "invTypes", "mapDenormalize", "mapRegions", "mapSolarSystems"); $type = ".sql.bz2"; foreach ($dbFiles as $file) { $dataURL = $url . "latest/" . $file . $type; try { exec("wget -q {$dataURL} -O {$cache}/{$file}{$type}"); exec("bzip2 -q -d {$cache}/{$file}{$type}"); } catch (\Exception $e) { echo "Error"; } $data = file_get_contents($cache . "/" . $file . ".sql"); $data = str_replace("ENGINE=InnoDB", "ENGINE=TokuDB", $data); $dataParts = explode(";\n", $data); foreach ($dataParts as $qry) { $query = $qry . ";"; $app->Db->execute($query); } unlink("{$cache}/{$file}.sql"); } $app->Storage->set("ccpdataMD5", $md5); } }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { //Init rena /** @var RenaApp $app */ $app = RenaApp::getInstance(); $startTime = time() + 3600; // Current time + 60 minutes $run = true; $stomp = new \Stomp($app->baseConfig->getConfig("server", "stomp"), $app->baseConfig->getConfig("username", "stomp"), $app->baseConfig->getConfig("password", "stomp")); $stomp->subscribe("/topic/kills", array("id" => $app->baseConfig->getConfig("queueName", "stomp", "projectRena"), "persistent" => "true", "ack" => "client", "prefetch-count" => 1)); do { $frame = $stomp->readFrame(); if (!empty($frame)) { $killdata = json_decode($frame->body, true); if (!empty($killdata)) { $app->StatsD->increment("stompReceived"); if (isset($killdata["_stringValue"])) { unset($killdata["_stringValue"]); } // Fix the killID $killdata["killID"] = (int) $killdata["killID"]; $json = json_encode($killdata, JSON_NUMERIC_CHECK); $hash = $app->CrestFunctions->generateCRESTHash($killdata); $inserted = $app->killmails->insertIntoKillmails($killdata["killID"], 0, $hash, "stomp", $json); if ($inserted > 0) { \Resque::enqueue("turbo", "\\ProjectRena\\Task\\Resque\\upgradeKillmail", array("killID" => $killdata["killID"])); } } $stomp->ack($frame->headers["message-id"]); } // Kill it after an hour if ($startTime <= time()) { $run = false; } } while ($run == true); }
public function __construct() { $this->app = RenaApp::getInstance(); $this->stomp = new Stomp($this->app->baseConfig->getConfig("server", "stomp"), $this->app->baseConfig->getConfig("username", "stomp"), $this->app->baseConfig->getConfig("password", "stomp")); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { // Enable the garbage collector since this is a long running process //gc_enable(); // Get the slim instance $app = RenaApp::getInstance(); $run = true; $cnt = 0; $cronjobs = scandir(__DIR__ . '/Cronjobs/'); do { $cnt++; if ($cnt > 50) { //gc_collect_cycles(); $cnt = 0; } foreach ($cronjobs as $key => $cron) { // Unset anything that isn't .php! if (!preg_match('/^(.+)\\.php$/', $cron, $match)) { unset($cronjobs[$key]); continue; } if (isset($match[1])) { $name = $match[1]; $md5 = md5($name); // If the script is currently running, skip to the next script if ($app->Cache->get($md5 . '_pid') !== false) { $pid = $app->Cache->get($md5 . '_pid'); $status = pcntl_waitpid($pid, $status, WNOHANG); if ($status == -1) { $app->Cache->delete($md5 . '_pid'); } usleep(500000); //continue; } // Get last time this cronjob ran $lastRan = $app->Cache->get($md5) > 0 ? $app->Cache->get($md5) : 0; // Current Time $currentTime = time(); // Load the cronjobs class and get the information needed $import = '\\ProjectRena\\Task\\Cronjobs\\' . $name; $class = new $import(); $interval = $class->getRunTimes(); // If the current time is larger than the lastRunTime and Interval, then we run it again! if ($currentTime > $lastRan + $interval) { $time = time(); $output->writeln("Time: {$time}: Running {$name} (Interval: {$interval})"); try { // Time to fork it all! $pid = pcntl_fork(); if ($pid === 0) { // Get the PID $pid = getmypid(); // Tell the cache that we're running the cronjobs will automatically remove it from the cache once they're done $app->Cache->set($md5 . '_pid', $pid); // Execute the cronjob $class->execute($pid, $md5); exit; } // Tell the cache when we ran last! $app->Cache->set($md5, time()); } catch (\Exception $e) { $output->writeln("ERROR!! (pid: " . getmypid() . ") " . $e->getMessage()); $run = false; posix_kill(getmygid(), 9); exit; } } } // Sleep for 500 milliseconds, so we don't go nuts with CPU usleep(500000); } } while ($run === true); }
/** * */ public function setUp() { $this->app = \ProjectRena\RenaApp::getInstance(); }
/** * Sets up the task (Setup $this->crap and such here) */ public function setUp() { $this->app = RenaApp::getInstance(); }
/** * Quick access to rendering templates, json, xml and probably more down the line. * * @param string $templateFile * @param array $dataArray * @param null $status * @param string $contentType */ function render($templateFile, $dataArray = array(), $status = null, $contentType = null) { $app = \ProjectRena\RenaApp::getInstance(); $app->out->render($templateFile, $dataArray, $status, $contentType); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $table = prompt("Table to create model for"); $this->description["description"] = prompt("Description"); if (!$table) { $output->writeln("Error, table name is not supplied."); exit; } // Setup the path and make sure it doesn't already exist $path = __DIR__ . "/../Model/Database/{$table}.php"; if (file_exists($path)) { return $output->writeln("Error, file already exists"); } // Load app $app = \ProjectRena\RenaApp::getInstance(); // Load the table, if it exists in the first place $tableColums = $app->Db->query("SHOW COLUMNS FROM {$table}"); // Generate the start of the model code $class = new PhpClass(); $class->setQualifiedName("ProjectRena\\Model\\Database\\{$table}")->setProperty(PhpProperty::create("app")->setVisibility("private")->setDescription("The Slim Application"))->setProperty(PhpProperty::create("db")->setVisibility("private")->setDescription("The database connection"))->setMethod(PhpMethod::create("__construct")->addParameter(PhpParameter::create("app")->setType("RenaApp"))->setBody("\$this->app = \$app;\n\r\n \$this->db = \$app->Db;\n"))->setDescription($this->description)->declareUse("ProjectRena\\RenaApp"); $nameFields = array(); $idFields = array(); foreach ($tableColums as $get) { // This is for the getByName selector(s) if (stristr($get["Field"], "name")) { $nameFields[] = $get["Field"]; } // This is for the getByID selector(s) if (strstr($get["Field"], "ID")) { $idFields[] = $get["Field"]; } } // Get generator foreach ($nameFields as $name) { // get * by Name $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}));")); } foreach ($idFields as $id) { // get * by ID, $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($id))->addParameter(PhpParameter::create($id)->setType("int"))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}));")); } foreach ($nameFields as $name) { foreach ($tableColums as $get) { // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID if ($get["Field"] == $name) { continue; } // Skip the id field if ($get["Field"] == "id") { continue; } $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));")); } } foreach ($idFields as $id) { foreach ($tableColums as $get) { // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID if ($get["Field"] == $id) { continue; } // Skip the id field if ($get["Field"] == "id") { continue; } $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));")); } } // Update generator foreach ($nameFields as $name) { foreach ($tableColums as $get) { // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID if ($get["Field"] == $name) { continue; } // Skip the id field if ($get["Field"] == "id") { continue; } $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));\r\n if(!empty(\$exists)){\r\n \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n ")); } } foreach ($idFields as $id) { foreach ($tableColums as $get) { // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID if ($get["Field"] == $id) { continue; } // Skip the id field if ($get["Field"] == "id") { continue; } $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));\r\n if(!empty(\$exists))\r\n {\r\n \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n ")); } } // Global insert generator (Yes it's ugly as shit..) $inserter = "public function insertInto" . ucfirst($table) . "("; foreach ($tableColums as $field) { // Skip the ID field if ($field["Field"] == "id") { continue; } $inserter .= "\${$field["Field"]}, "; } $inserter = rtrim(trim($inserter), ",") . ")"; $inserter .= "{"; $inserter .= "\$this->db->execute(\"INSERT INTO {$table} ("; foreach ($tableColums as $field) { if ($field["Field"] == "id") { continue; } $inserter .= $field["Field"] . ", "; } $inserter = rtrim(trim($inserter), ",") . ") "; $inserter .= "VALUES ("; foreach ($tableColums as $field) { if ($field["Field"] == "id") { continue; } $inserter .= ":" . $field["Field"] . ", "; } $inserter = rtrim(trim($inserter), ",") . ")\", "; $inserter .= "array("; foreach ($tableColums as $field) { if ($field["Field"] == "id") { continue; } $inserter .= "\":" . $field["Field"] . "\" => \${$field["Field"]}, "; } $inserter = rtrim(trim($inserter), ",") . "));"; $inserter .= "}}"; $generator = new CodeFileGenerator(); $code = $generator->generate($class); $code = rtrim(trim($code), "}"); $code .= $inserter; $formatter = new Formatter(); $code = $formatter->format($code); file_put_contents($path, $code); chmod($path, 0777); $output->writeln("Model created: {$path}"); }