GetHolidayCommand::execute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 20
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 12
nc 1
nop 2
1
<?php
2
/*
3
 * This file is part of the Slince/China package.
4
 *
5
 * (c) Slince <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace China\Command;
12
13
use China\Holiday\Date;
14
use China\Holiday\Holiday;
15
use China\Holiday\HolidayInterface;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\Console\Style\SymfonyStyle;
19
use Symfony\Component\DomCrawler\Crawler;
20
21
class GetHolidayCommand extends CrawlCommand
22
{
23
    /**
24
     * 节假日资源地址
25
     *
26
     * @var string
27
     */
28
    const URL = 'http://www.sojson.com/time/holiday.html';
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function configure()
34
    {
35
        $this->setName('crawl:holiday');
36
        $this->setDescription('采集节假日数据');
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function execute(InputInterface $input, OutputInterface $output)
43
    {
44
        $style = new SymfonyStyle($input, $output);
45
46
        $outputFile = static::RESOURCE_DIR.'/holidays.json';
47
48
        $crawler = $this->getClient()->request('GET', static::URL);
49
        $holidays = $crawler->filter('.festival_list')->each(function(Crawler $node){
50
            $fontNode = $node->filter('font');
51
            $date = $this->parseToDate(strstr($node->text(), '['));
52
            $date = new Date($date[0], $date[1]);
53
            $type = $this->convertColorToType($fontNode->attr('color'));
54
55
            return new Holiday($fontNode->text(), $type, $date);
56
        });
57
58
        $this->filesystem->dumpFile($outputFile, \GuzzleHttp\json_encode($holidays, JSON_UNESCAPED_UNICODE));
59
60
        $style->writeln(sprintf('<info>Crawl completed, please check the file at "%s"</info>', realpath($outputFile)));
61
    }
62
63
    protected function parseToDate($dateString)
64
    {
65
        return explode('/', trim($dateString, ']['));
66
    }
67
68
    protected function convertColorToType($class)
69
    {
70
        $type = '';
71
        switch ($class) {
72
            case 'red':
73
                $type = HolidayInterface::TYPE_TRADITIONAL;
74
                break;
75
76
            case 'green':
77
                $type = HolidayInterface::TYPE_INTERNATIONAL;
78
                break;
79
80
            case 'blue':
81
                $type = HolidayInterface::TYPE_SOLAR_TERM;
82
                break;
83
        }
84
85
        return $type;
86
    }
87
}