Skip to content

Commit

Permalink
first version
Browse files Browse the repository at this point in the history
  • Loading branch information
bigperson committed Jun 9, 2017
0 parents commit b44bc0e
Show file tree
Hide file tree
Showing 18 changed files with 840 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
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Anton Kartsev aka Bigperson <anton@klin.ru>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
103 changes: 103 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Laravel VK Geo
[![Packagist Version](https://img.shields.io/packagist/v/bigperson/laravel-vk-geo.svg)](https://packagist.org/packages/bigperson/laravel-vk-geo)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/bigperson/laravel-vk-geo/master/LICENSE)

Пакет предоставляет удобный способ ипорта стран, регионов и городов используя api vk.com.

Пакет использует [atehnix/vk-client](https://github.com/atehnix/vk-client) для выполнения запросов. Используются **синхронные запросы**, если вы хотите постоянно обновлять данные, то используйте пакет [atehnix/laravel-vk-requester](https://github.com/atehnix/laravel-vk-requester)

## Сожержание
* Установка
* Импорт данных
* Использование

## Установка
Вы можете установить данный пакет с помощью oomposer:

```
composer require bigperson/laravel-vk-geo
```

Далее необходимо зарегистровать новый сервис-провайдер в config/app.php:

```php
...
'providers' => [
...
Bigperson\VkGeo\VkGeoServiceProvider::class,
],
...
```

### Конфигурация
Сначала необходимо создать необходимые таблицы в базе данных, для этого импортируйте файлы миграций из пакета используя artisan:

```
php artisan vendor:publish --provider=Bigperson\VkGeo\VkGeoServiceProvider
```
Также создастся файл конфигурации `config/vk-geo.php`. После чего необходимо применить миграции:
```
php artisan migrate
```
В `.env` необходимо добавить, данные вашего vk приложения:
```
VKONTAKTE_KEY=
VKONTAKTE_SECRET=
VKONTAKTE_REDIRECT_URI=
```
Также для выполнения импорта получить токен ([Где взять api токен?](https://github.com/atehnix/laravel-vk-requester#Где-взять-api-токен)) приложения и добавить в `.env`:
```
VKONTAKTE_TOKEN=
```
Либо переопределить токен в `config/vk-geo.php`.

## Импорт осуществляется через консоль.
### Импорт всех стран
```
php artisan vk:import-countries
```
### Импорт регионов
Импорт регионов для всех стран
```
php artisan vk:import-regions
```
Возможен также и импорт для отдельных стран по их id
```
php artisan vk:import-regions --countryId=1 --countryId=2
```

### Импорт городов

Импорт городов для отдельных стран
```
php artisan vk:import-cities --countryId=1 --countryId=2
```
Импорт городов для отдельных регионов
```
php artisan vk:import-cities --regionId=1014032 --regionId=1048584
```

Если вам нужен импорт для всех стран и всех регионов, то можно запустить компанду без параметров, но данный способ не тестировался, и скорее всего будут ошибки связанные с ответом от серверов VK. Вы также можете переопределить любую из консольных команд, создав собсвтенные и отнаследовавшись от оригинальных.

## Использование

Использовать пакет достаточно просто. В пакет входят eloquent модели города, региона и страны (City, Region, Country). Вы можете вызывать модели в контроллерах:
```php
namespace App\Http\Controllers;

use Bigperson\VkGeo\Models\City;

class Controller
{
protected function show($name){

$city = City::where('title', $name)->first();

}
}
```
У каждой модели есть `title`, `id`, у городов есть `area` (район), также настроенны связи между моделями. При необходимости можете также переопределить их.


## Лицензия
[MIT](https://raw.github.com/bigperson/laravel-vk-geo/master/LICENSE)
35 changes: 35 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "bigperson/laravel-vk-geo",
"description": "Parse countries, regions and cities from vk.com api",
"keywords": [
"laravel",
"php",
"queue",
"api",
"client",
"vk",
"vk.com",
"vkontakte",
"geo",
"cities",
"regions",
"countries"
],
"require": {
"php": ">=5.5.9",
"laravel/framework": "~5.2.0|~5.3.0|~5.4.0",
"atehnix/vk-client": "^1.0.0"
},
"license": "MIT",
"authors": [
{
"name": "Anton Kartsev",
"email": "anton@klin.ru"
}
],
"autoload": {
"psr-4": {
"Bigperson\\VkGeo\\": "src/"
}
}
}
33 changes: 33 additions & 0 deletions publish/config/vk-geo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| API Version
|--------------------------------------------------------------------------
|
| Version Vkontakte API, which must be used in request.
|
*/
'version' => '5.53',

/*
|--------------------------------------------------------------------------
| Table prefix
|--------------------------------------------------------------------------
|
| The name of the tables models.
|
*/
'prefix' => 'vk_',

/*
|--------------------------------------------------------------------------
| Delay before request
|--------------------------------------------------------------------------
|
| The delay before sending the request in milliseconds.
|
*/

'delay' => 350,
];
48 changes: 48 additions & 0 deletions publish/database/2017_06_09_090720_create_cities_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCitiesTable extends Migration
{
/**
* @var string
*/
private $table;

/**
* CreateCitiesTable constructor.
*/
public function __construct()
{
$this->table = config('vk-geo.prefix', '').'cities';
}

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id');
$table->integer('region_id');
$table->string('title');
$table->string('area')->nullable();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
45 changes: 45 additions & 0 deletions publish/database/2017_06_09_090720_create_countries_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCountriesTable extends Migration
{
/**
* @var string
*/
private $table;

/**
* CreateCitiesTable constructor.
*/
public function __construct()
{
$this->table = config('vk-geo.prefix', '').'countries';
}

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
46 changes: 46 additions & 0 deletions publish/database/2017_06_09_090720_create_regions_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRegionsTable extends Migration
{
/**
* @var string
*/
private $table;

/**
* CreateCitiesTable constructor.
*/
public function __construct()
{
$this->table = config('vk-geo.prefix', '').'regions';
}

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id');
$table->string('title');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
37 changes: 37 additions & 0 deletions src/Commands/AbstractCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace Bigperson\VkGeo\Commands;

use ATehnix\VkClient\Client;
use ATehnix\VkClient\Requests\Request;
use Bigperson\VkGeo\Models\Country;
use Bigperson\VkGeo\Models\Region;
use Illuminate\Console\Command;

abstract class AbstractCommand extends Command
{
/**
* @var Client
*/
protected $client;

/**
* ImportCountryCommand constructor.
*
* @param Client $client
*/
public function __construct(Client $client)
{
parent::__construct();

$this->client = $client;
}

/**
* @param $table
*/
protected function clearTable($table)
{
\DB::table(config('vk-geo.prefix', '').$table)->delete();
}
}
Loading

0 comments on commit b44bc0e

Please sign in to comment.