ImportClient.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace FD3;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Input\InputArgument;
  6. use Symfony\Component\Console\Input\InputOption;
  7. use Symfony\Component\Console\Output\OutputInterface;
  8. use GuzzleHttp\Client as GuzzClient;
  9. use GuzzleHttp\Exception\ServerException as RequestException;
  10. use GuzzleHttp\Psr7;
  11. class ImportClient extends Command{
  12. protected function configure()
  13. {
  14. $this
  15. ->setName('import:client')
  16. ->setDescription('.')
  17. ->setHelp('Client.json shuld be a valid json file, probably looking like the following example:
  18. [
  19. {"externalId": "abcdefg","name": "Name of client","address": "Address of client"},
  20. {"externalId": "abcdefg","name": "Name of client","address": "Address of client"},
  21. {"externalId": "abcdefg","name": "Name of client","address": "Address of client"},
  22. {"externalId": "abcdefg","name": "Name of client","address": "Address of client"}
  23. ]
  24. ')
  25. ->addArgument('base_url', InputArgument::REQUIRED, 'The base url of the FD3 Client.')
  26. ->addArgument('data_file.json', InputArgument::OPTIONAL, 'The data source from where to get data.', "Client.json")
  27. ->addOption('uri', null, InputOption::VALUE_REQUIRED, 'uri after the base_url for the complete URL', '/api/clients.json')
  28. ->addOption('user', null, InputOption::VALUE_REQUIRED, 'The FD3 Username.', 'admin')
  29. ->addOption('pass', null, InputOption::VALUE_REQUIRED, 'The FD3 Password.', 'adminpass')
  30. // ->addOption('source-name', null, InputOption::VALUE_REQUIRED, 'Rename the source to this name.', "upstream")
  31. ;
  32. }
  33. protected function execute(InputInterface $input, OutputInterface $output)
  34. {
  35. $base_url = $input->getArgument("base_url");
  36. $uri = $input->getOption("uri");
  37. $user = $input->getOption('user');
  38. $pass = $input->getOption('pass');
  39. $file = $input->getArgument("data_file.json");
  40. $url = $base_url.$uri;
  41. $parser = new \JsonCollectionParser\Parser();
  42. $parser->parse($file, function($data) use ($url, $user, $pass){
  43. $client = new GuzzClient();
  44. try{
  45. $res = $client->request("POST", $url, [ 'auth' => [$user, $pass], 'body' => json_encode($data) ]);
  46. echo $res->getBody();
  47. } catch (RequestException $e) {
  48. echo Psr7\str($e->getRequest());
  49. if ($e->hasResponse()) {
  50. echo Psr7\str($e->getResponse());
  51. }
  52. }
  53. }
  54. );
  55. }
  56. }