summaryrefslogtreecommitdiff
path: root/src/NeonXP/DozorApi.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/NeonXP/DozorApi.php')
-rw-r--r--src/NeonXP/DozorApi.php112
1 files changed, 112 insertions, 0 deletions
diff --git a/src/NeonXP/DozorApi.php b/src/NeonXP/DozorApi.php
new file mode 100644
index 0000000..c3b492e
--- /dev/null
+++ b/src/NeonXP/DozorApi.php
@@ -0,0 +1,112 @@
+<?php
+/**
+ * @author Alexander "NeonXP" Kiryukhin
+ */
+namespace NeonXP;
+use Doctrine\Common\Cache\CacheProvider;
+use NeonXP\TelegramApi\Types\Chat;
+use Symfony\Component\CssSelector\Node\AbstractNode;
+use Symfony\Component\DomCrawler\Crawler;
+
+
+/**
+ * Class DozorApi
+ * @package NeonXP
+ */
+class DozorApi
+{
+ /**
+ * @var CacheProvider
+ */
+ private $cache;
+
+ /**
+ * DozorApi constructor.
+ * @param CacheProvider $cache
+ */
+ public function __construct(CacheProvider $cache)
+ {
+ $this->cache = $cache;
+ }
+
+ public function sendCode(Chat $chat, $code)
+ {
+ $params = [
+ "log" => 'on',
+ "mes" => '',
+ "legend" => 'on',
+ "nostat" => '',
+ "notext" => '',
+ "refresh" => '0',
+ "bonus" => '',
+ "kladMap" => '',
+ "notags" => '',
+ "cod" => $code,
+ "action" => 'entcod',
+ ];
+ $data = http_build_query($params);
+ $context = [
+ 'http' => [
+ 'method' => 'POST',
+ 'header' => 'Content-type: application/x-www-form-urlencoded',
+ 'content' => $data
+ ]
+ ];
+ $context = stream_context_create($context);
+ $result = file_get_contents($this->getLink($chat), false, $context);
+
+ return $this->parseResult($result);
+ }
+
+ private function parseResult($html)
+ {
+ $crawler = new Crawler($html);
+
+ $answer = [
+ $this->parseCodeEnter($html),
+ $this->parseTask($crawler)
+ ];
+
+ $answer = array_merge($answer, $this->parseCodes($crawler));
+ $answer = array_filter($answer);
+
+ return implode(PHP_EOL, $answer);
+ }
+
+ private function parseCodeEnter($html)
+ {
+ $result = iconv('cp1251', 'utf8', $html);
+ $result = mb_strtolower($result, 'utf8');
+ if (strpos($result, 'код принят')) {
+ $result = 'Код принят';
+ } else {
+ $result = 'Код НЕ принят';
+ }
+
+ return $result;
+ }
+
+ private function parseTask(Crawler $crawler)
+ {
+ return $crawler->filter('body > p')->reduce(function ($node) {
+ return strpos($node->text(), 'Задание ');
+ })->text();
+ }
+
+ private function parseCodes(Crawler $crawler)
+ {
+ $codesHtml = $crawler->filter('body > .dcodes')->html();
+ $codesHtml = preg_replace('/\<span\ style\=\"color\:red\"\>(.+?)\<\/span\>/i', '*[$1]*', $codesHtml);
+ $codesHtml = preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $codesHtml);
+ $codesHtml = strip_tags($codesHtml);
+ $codesHtml = explode(PHP_EOL, $codesHtml);
+ array_shift($codesHtml);
+
+ return $codesHtml;
+ }
+
+ private function getLink(Chat $chat)
+ {
+ return $this->cache->fetch("link_{$chat->getId()}");
+ }
+} \ No newline at end of file