Skip to content

Instantly share code, notes, and snippets.

@Cifro
Forked from fprochazka/HomepagePresenter.php
Created June 2, 2011 07:29
Show Gist options
  • Save Cifro/1004064 to your computer and use it in GitHub Desktop.
Save Cifro/1004064 to your computer and use it in GitHub Desktop.
Mobile device detection in Nette
common:
# ...
services:
detector:
class: MobileDetector
arguments: ["@httpRequest"]
# ...
<?php
class HomepagePresenter extends BasePresenter
{
public function actionDefault()
{
$detector = $this->context->detector;
if ($detector->isMobile()) {
$this->redirect("mobile");
}
}
}
<?php
/**
* Mobile detector service.
* @author Vic Stanciu, Vaclav Bohac
* @license MIT License
*/
/**
* Mobile detector.
*
* Original class: http://code.google.com/p/php-mobile-detect/.
*
* @author Vic Stanciu, Vaclav Bohac
*/
class MobileDetector extends Nette\Object
{
/** @var Nette\Http\IRequest */
private $httpRequest;
/** @var array */
protected $devices = array (
"android" => "android",
"blackberry" => "blackberry",
"iphone" => "(iphone|ipod)",
"opera" => "opera mini",
"palm" => "(avantgo|blazer|elaine|hiptop|palm|plucker|xiino)",
"windows" => "windows ce; (iemobile|ppc|smartphone)",
"generic" => "(kindle|mobile|mmp|midp|o2|pda|pocket|psp|symbian|smartphone|treo|up.browser|up.link|vodafone|wap)"
);
/** @var array */
private $wapTypes = array (
"text" => "text/vnd.wap.wml",
"app" => "application/vnd.wap.xhtml+xml"
);
/**
* @param Nette\Http\IRequest $httpRequest
*/
public function __construct(Nette\Http\IRequest $httpRequest)
{
$this->httpRequest = $httpRequest;
}
/**
* Get HttpRequest.
* @return Nette\Http\IRequest
*/
public function getRequest()
{
return $this->httpRequest;
}
/**
* Is client a mobile device?
* @return bool
*/
public function isMobile()
{
$request = $this->getRequest();
if ($request->getHeader("x-wap-profile") || $request->getHeader("profile")) {
return True;
}
$accept = $request->getHeader("accept");
foreach ($this->wapTypes as $type) {
if (strpos($accept, $type) !== False) {
return True;
}
}
foreach (array_keys($this->devices) as $device) {
if ($this->isDevice($device)) {
return True;
}
}
return False;
}
/**
* Is user agent given device (Android, iPhone, ...)?
* @return bool
*/
public function isDevice($device)
{
if (!isset($this->devices[$device])) {
throw new Nette\InvalidArgumentException("Device '$device' not supported.");
} else {
$header = $this->getRequest()->getHeader("user-agent");
return (bool) Nette\Utils\Strings::match($header, "~{$this->devices[$device]}~i");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment