Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ProklUng committed May 9, 2021
0 parents commit df2c654
Show file tree
Hide file tree
Showing 19 changed files with 1,353 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
/vendor/
composer.lock
193 changes: 193 additions & 0 deletions Command/MakeFixtures.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<?php

namespace Prokl\InstagramParserRapidApiBundle\Command;

use Exception;
use Prokl\InstagramParserRapidApiBundle\Services\Exceptions\InstagramTransportException;
use Prokl\InstagramParserRapidApiBundle\Services\Interfaces\RetrieverInstagramDataInterface;
use Prokl\InstagramParserRapidApiBundle\Services\UserInfoRetriever;
use Psr\Cache\InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
* Class MakeFixtures
* Создание фикстур Инстаграма.
* @package Prokl\InstagramParserRapidApiBundle\Command
*
* @since 25.02.2021
*/
class MakeFixtures extends Command
{
/**
* @var RetrieverInstagramDataInterface $parser Получение данных о картинках.
*/
private $parser;

/**
* @var UserInfoRetriever $userIdRetriever Извлекатель информации о пользователе.
*/
private $userIdRetriever;

/**
* @var string $username Код эккаунта.
*/
private $username;

/**
* @var string $fixtureResponsePath Путь к фикстуре запроса картинок.
*/
private $fixtureResponsePath;

/**
* @var string $fixtureUserPath Путь к фикстуре запроса данных пользователя.
*/
private $fixtureUserPath;

/**
* @var OutputInterface $output
*/
private $output;

/**
* MakeFixtures constructor.
*
* @param RetrieverInstagramDataInterface $parser Получение данных о картинках.
* @param UserInfoRetriever $userIdRetriever Извлекатель информации о пользователе.
* @param string $username Код эккаунта.
* @param string $fixtureResponsePath Путь к фикстуре запроса картинок.
* @param string $fixtureUserPath Путь к фикстуре запроса данных пользователя.
*/
public function __construct(
RetrieverInstagramDataInterface $parser,
UserInfoRetriever $userIdRetriever,
string $username,
string $fixtureResponsePath,
string $fixtureUserPath
) {
$this->parser = $parser;
$this->userIdRetriever = $userIdRetriever;
$this->username = $username;
$this->fixtureResponsePath = $fixtureResponsePath;
$this->fixtureUserPath = $fixtureUserPath;

parent::__construct();
}

/**
* Конфигурация.
*
* @return void
*/
protected function configure() : void
{
$this->setName('make:instagram-fixtures')
->setDescription('Make Instagram fixtures')
->addArgument('username', InputArgument::OPTIONAL, 'Instagram user name')
;
}

/**
* Исполнение команды.
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
* @throws Exception
* @throws InvalidArgumentException
*/
protected function execute(InputInterface $input, OutputInterface $output) : void
{
$this->output = $output;

$output->writeln('Начало процесса создания фикстур.');

/** @var string $className Оригинальный класс. */
$username = $input->getArgument('username') ?? $this->username;

$userId = $this->makeUserFixture($username);
if (!$userId) {
return;
}

if (!$this->makeResponseFixture($userId)) {
return;
}

$output->writeln('Фикстуры созданы успешно.');
}

/**
* @param string $username Код эккаунта.
*
* @return string
*
* @throws InstagramTransportException | RuntimeException | InvalidArgumentException
*/
private function makeUserFixture(string $username) : string
{
$this->userIdRetriever->setUseMock(false);
$this->userIdRetriever->setUserName($username);

$allData = $this->userIdRetriever->getAllData();

if (!$this->write($this->fixtureUserPath, $allData)) {
$this->output->writeln('Ошибка записи данных в фикстуру ' . $this->fixtureUserPath);
return '';
}

$this->output->writeln('Фикстура данных пользователя создана.');

if (!array_key_exists('id', $allData)) {
throw new RuntimeException(
'В ответе на данные пользователя отсутствует ключ ID.'
);
}

return (string)$allData['id'];
}

/**
* @param string $userId ID эккаунта.
*
* @return boolean
*
* @throws Exception
*/
private function makeResponseFixture(string $userId) : bool
{
$this->parser->setUseMock(false);
$this->parser->setUserId($userId);

$allData = $this->parser->query();

if (!$this->write($this->fixtureResponsePath, $allData)) {
$this->output->writeln('Ошибка записи данных в фикстуру ' . $this->fixtureUserPath);
return false;
}

$this->output->writeln('Фикстура ответа Инстаграма создана.');

return true;
}

/**
* Записать контент в файл.
*
* @param string $filename Путь к файлу.
* @param array $content Контент.
*
* @return boolean
*/
private function write(string $filename, array $content) : bool
{
return (bool)file_put_contents(
$_SERVER['DOCUMENT_ROOT'] . $filename,
json_encode($content)
);
}
}
55 changes: 55 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace Prokl\InstagramParserRapidApiBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
* Class Configuration
* @package Prokl\InstagramParserRapidApiBundle\DependencyInjection
*
* @since 04.12.2020
*
* @psalm-suppress PossiblyUndefinedMethod
*/
class Configuration implements ConfigurationInterface
{
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('rapid_api_instagram_parser');
$rootNode = $treeBuilder->getRootNode();

$rootNode
->children()
->arrayNode('defaults')
->useAttributeAsKey('name')
->prototype('boolean')->end()
->defaultValue([
'enabled' => false,
])
->end()
->end()

->children()
->booleanNode('mock')->defaultValue(false)->end()
->scalarNode('instagram_user_id')->end()
->scalarNode('instagram_user_name')->defaultValue('')->end()
->scalarNode('rapid_api_key')->end()
->scalarNode('fixture_response_path')->defaultValue(
'/local/classes/Bundles/InstagramParserRapidApiBundle/Fixture/response.txt'
)->end()
->scalarNode('fixture_user_path')->defaultValue(
'/local/classes/Bundles/InstagramParserRapidApiBundle/Fixture/user.txt'
)->end()
->scalarNode('cache_path')->defaultValue('cache/instagram-parser')->end()
->scalarNode('cache_ttl')->defaultValue(86400)->end()
->scalarNode('cache_user_data_ttl')->defaultValue(31536000)->end()
->end();

return $treeBuilder;
}
}
59 changes: 59 additions & 0 deletions DependencyInjection/InstagramParserRapidApiExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Prokl\InstagramParserRapidApiBundle\DependencyInjection;

use Exception;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
* Class InstagramParserRapidApiExtension
* @package Local\Bundles\InstagramParserRapidApi\DependencyInjection
*
* @since 22.02.2021
*/
class InstagramParserRapidApiExtension extends Extension
{
private const DIR_CONFIG = '/../Resources/config';

/**
* @inheritDoc
* @throws Exception
*/
public function load(array $configs, ContainerBuilder $container) : void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

if (!$config['defaults']['enabled']) {
return;
}

$container->setParameter('instagram_parser_rapid_api.instagram_user_id', $config['instagram_user_id']);
$container->setParameter('instagram_parser_rapid_api.instagram_user_name', $config['instagram_user_name']);
$container->setParameter('instagram_parser_rapid_api.rapid_api_key', $config['rapid_api_key']);
$container->setParameter('instagram_parser_rapid_api.cache_ttl', $config['cache_ttl']);
$container->setParameter('instagram_parser_rapid_api.cache_user_data_ttl', $config['cache_user_data_ttl']);
$container->setParameter('instagram_parser_rapid_api.cache_path', $config['cache_path']);
$container->setParameter('instagram_parser_rapid_api.mock', $config['mock']);
$container->setParameter('instagram_parser_rapid_api.fixture_response_path', $config['fixture_response_path']);
$container->setParameter('instagram_parser_rapid_api.fixture_user_path', $config['fixture_user_path']);

$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__ . self::DIR_CONFIG)
);

$loader->load('services.yaml');
}

/**
* @inheritDoc
*/
public function getAlias()
{
return 'instagram_parser_rapid_api';
}
}
1 change: 1 addition & 0 deletions Fixture/response.txt

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Fixture/user.txt

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions InstagramParserRapidApiBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Prokl\InstagramParserRapidApiBundle;

use Prokl\InstagramParserRapidApiBundle\DependencyInjection\InstagramParserRapidApiExtension;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
* Class InstagramParserRapidApiBundle
* @package Local\Bundles\InstagramParserRapidApiBundle
*
* @since 22.02.2021
*/
class InstagramParserRapidApiBundle extends Bundle
{
/**
* @inheritDoc
*/
public function getContainerExtension()
{
if ($this->extension === null) {
$this->extension = new InstagramParserRapidApiExtension();
}

return $this->extension;
}
}
Loading

0 comments on commit df2c654

Please sign in to comment.