Skip to content

Instantly share code, notes, and snippets.

@blongden
Created December 22, 2014 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blongden/6d20ba10aece17f2d447 to your computer and use it in GitHub Desktop.
Save blongden/6d20ba10aece17f2d447 to your computer and use it in GitHub Desktop.
{
"require": {
"php": ">=5.4.0",
"elasticsearch/elasticsearch": "~1.3"
}
}
<?php
require_once 'vendor/autoload.php';
run();
function run()
{
$es = elasticClient();
createProductsIndex($es);
$oauth = getOAuth();
$products = queryProducts($oauth);
foreach ($products as $product) {
indexProduct($es, $oauth, $product);
}
}
function elasticClient()
{
return new Elasticsearch\Client(
[
'hosts' => [
'https://szj7ontc09:j0iam1qjhk@httplabsstaging-8492688318.eu-west-1.bonsai.io:443'
]
]
);
}
function indexProduct($es, $oauth, $product)
{
echo "Indexing product {$product->entity_id}; '{$product->sku}'; '{$product->name}'".PHP_EOL;
$product->categories = queryProductData($oauth, $product->entity_id, 'categories');
$product->images = queryProductData($oauth, $product->entity_id, 'images');
$es->index(
[
'body' => $product,
'index' => 'products',
'type' => 'product'
]
);
}
function createProductsIndex($es)
{
$es->indices()->delete(['index' => 'products']);
$es->indices()->create(['index' => 'products']);
}
function queryProducts($oauth)
{
try {
$result = $oauth->fetch('http://magentofrontend.dev/api/rest/products', array(), 'GET', array('Content-Type' => 'application/json'));
if ($result) {
return json_decode($oauth->getLastResponse());
}
} catch(OAuthException $e) {
print_r($e);
}
return [];
}
function queryProductData($oauth, $id, $resource)
{
$result = $oauth->fetch("http://magentofrontend.dev/api/rest/products/{$id}/{$resource}", array(), 'GET', array('Content-Type' => 'application/json'));
if ($result) {
$data = json_decode($oauth->getLastResponse());
return $data;
}
}
function getOAuth()
{
$oauth = new OAuth('9305535f38b6eb02cb3041755b0ffd41', 'ccb72ae66658a11e5f60639782324fcd');
$oauth->enableDebug();
if(file_exists('token')) {
$token = json_decode(file_get_contents('token'));
$oauth->setToken($token->oauth_token, $token->oauth_token_secret);
return $oauth;
}
$rtoken = $oauth->getRequestToken('http://magentofrontend.dev/oauth/initiate', '');
echo '1. Click this link to authorize, '.'http://magentofrontend.dev/admin/oauth_authorize?oauth_token='.$rtoken['oauth_token'].PHP_EOL;
echo '2. Enter "Verifier code": ';
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
$oauth->setToken($rtoken['oauth_token'], $rtoken['oauth_token_secret']);
$token = $oauth->getAccessToken('http://magentofrontend.dev/oauth/token', '', trim($line));
file_put_contents('token', json_encode($token));
$oauth->setToken($token['oauth_token'], $token['oauth_token_secret']);
return $oauth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment