SharrreCounterController.php in Share Message 8
File
src/Controller/SharrreCounterController.php
View source
<?php
namespace Drupal\sharemessage\Controller;
use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\Exception\BadResponseException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class SharrreCounterController extends ControllerBase {
protected $client;
public function getCounter(Request $request) {
$json = [
'url' => $request
->get('url'),
'count' => 0,
];
$url = urlencode($json['url']);
$type = $request
->get('type');
if (filter_var($json['url'], FILTER_VALIDATE_URL)) {
if ($type == 'googlePlus') {
$json['count'] = $this
->getCounterGooglePlus($url);
}
elseif ($type == 'stumbleupon') {
$json['count'] = $this
->getCounterStumbleupon($url);
}
}
return new JsonResponse($json);
}
protected function getCounterGooglePlus($url) {
$contents = $this
->parse('https://plusone.google.com/u/0/_/+1/fastbutton?url=' . $url . '&count=true');
preg_match('/window\\.__SSR = {c: ([\\d]+)/', $contents, $matches);
if (isset($matches[0])) {
return (int) str_replace('window.__SSR = {c: ', '', $matches[0]);
}
}
protected function getCounterStumbleupon($url) {
$content = $this
->parse("http://www.stumbleupon.com/services/1.01/badge.getinfo?url={$url}");
$result = json_decode($content);
if (isset($result->result->views)) {
return $result->result->views;
}
}
public function parse($enc_url) {
try {
$response = \Drupal::httpClient()
->request('GET', $enc_url);
} catch (BadResponseException $e) {
$error = $e
->getResponse()
->json();
watchdog_exception('sharrre', $e, $error['error']['message']);
return;
}
return $response
->getBody()
->getContents();
}
}