public function __construct(Browscap $parser, $expectedType = '') { $this->parser = $parser; if ($parser->getCache()->getType() === null) { throw new InvalidArgumentException('You need to warm-up the cache first to use this provider'); } if ($expectedType !== $parser->getCache()->getType()) { throw new InvalidArgumentException('Expected the "' . $expectedType . '" data file. Instead got the "' . $parser->getCache()->getType() . '" data file'); } }
protected function getParserWithColdCache($type) { $filename = 'php_browscap.ini'; if ($type != '') { $filename = $type . '_' . $filename; } $cache = new \WurflCache\Adapter\Memory(); $browscap = new Browscap(); $browscap->setCache($cache); return $browscap; }
/** * Register browscap. * * @author Morten Rugaard <*****@*****.**> * * @return void */ protected function registerBrowscap() { $this->app->singleton(Browscap::class, function ($app) { $browscap = new Browscap(); // Cache for 90 days $browscap->setCache(new BrowscapCache(new CacheFile([CacheFile::DIR => storage_path('framework/browscap')])), 7776000); // Automatically check for updates $browscap->update(); return $browscap; }); }
/** * @dataProvider providerUserAgent * @depends testCheckProperties * @group compare * * @param string $userAgent */ public function testCompare($userAgent) { $libResult = get_browser($userAgent); $bcResult = self::$object->getBrowser($userAgent); foreach (array_keys($this->properties) as $bcProp) { if (in_array($bcProp, array('browser_name_regex', 'browser_name_pattern', 'Parent'))) { continue; } $bcProp = strtolower($bcProp); self::assertObjectHasAttribute($bcProp, $libResult, 'Actual library result does not have "' . $bcProp . '" property'); self::assertObjectHasAttribute($bcProp, $bcResult, 'Actual browscap result does not have "' . $bcProp . '" property'); $libValue = (string) $libResult->{$bcProp}; $bcValue = (string) $bcResult->{$bcProp}; self::assertSame($libValue, $bcValue, 'Expected actual "' . $bcProp . '" to be "' . $libValue . '" (was "' . $bcValue . '"; used pattern: ' . $bcResult->browser_name_pattern . ')'); } }
/** * @dataProvider userAgentDataProvider * @coversNothing * * @param string $userAgent * @param array $expectedProperties * @param bool $lite * @param bool $standard * * @throws \Exception * @throws \BrowscapPHP\Exception * * @group intergration * @group useragenttest * @group lite */ public function testUserAgentsLite($userAgent, $expectedProperties, $lite = true, $standard = true) { if (!is_array($expectedProperties) || !count($expectedProperties)) { self::markTestSkipped('Could not run test - no properties were defined to test'); } if (!$lite) { self::markTestSkipped('Test skipped - Browser/Platform/Version not defined for Lite Mode'); } static $updatedLiteCache = false; if (!$updatedLiteCache) { self::$browscap->convertFile(self::$buildFolder . '/lite_php_browscap.ini'); $updatedLiteCache = true; } $actualProps = (array) self::$browscap->getBrowser($userAgent); foreach ($expectedProperties as $propName => $propValue) { if (!self::$propertyHolder->isOutputProperty($propName)) { continue; } if (!self::$propertyHolder->isLiteModeProperty($propName)) { continue; } $propName = strtolower($propName); self::assertArrayHasKey($propName, $actualProps, 'Actual properties did not have "' . $propName . '" property'); self::assertSame($propValue, $actualProps[$propName], 'Expected actual "' . $propName . '" to be "' . $propValue . '" (was "' . $actualProps[$propName] . '"; used pattern: ' . $actualProps['browser_name_pattern'] . ')'); } }
/** * @param string $ua * @param string $mode * * @return string */ private function testUA($ua, $mode) { $data = $this->browscap->getBrowser($ua, true); if ($mode === GrepCommand::MODE_UNMATCHED && $data['Browser'] === 'Default Browser') { $this->logger->info($ua); return GrepCommand::MODE_UNMATCHED; } elseif ($mode === GrepCommand::MODE_MATCHED && $data['Browser'] !== 'Default Browser') { $this->logger->info($ua); return GrepCommand::MODE_MATCHED; } return GrepCommand::FOUND_INVISIBLE; }
/** * */ public function testGetBrowserWithDefaultResult() { $formatter = $this->getMockBuilder(\BrowscapPHP\Formatter\PhpGetBrowser::class)->disableOriginalConstructor()->setMethods(['getData'])->getMock(); $formatter->expects(self::once())->method('getData')->will(self::returnValue(null)); $parser = $this->getMockBuilder(\BrowscapPHP\Parser\Ini::class)->disableOriginalConstructor()->setMethods(['getBrowser'])->getMock(); $parser->expects(self::once())->method('getBrowser')->will(self::returnValue(null)); $cache = $this->getMockBuilder(\BrowscapPHP\Cache\BrowscapCache::class)->disableOriginalConstructor()->setMethods(['getVersion'])->getMock(); $cache->expects(self::once())->method('getVersion')->will(self::returnValue(1)); $this->object->setFormatter($formatter); $this->object->setParser($parser); $this->object->setCache($cache); $result = $this->object->getBrowser('Mozilla/5.0 (compatible; Ask Jeeves/Teoma)'); self::assertNull($result); }
/** * */ public function testCheckUpdateWithNewerVersion() { $logger = $this->getMock('\\Monolog\\Logger', array(), array(), '', false); $this->object->setLogger($logger); $loader = $this->getMock('\\BrowscapPHP\\Helper\\IniLoader', array('setRemoteFilename', 'setOptions', 'setLogger', 'load', 'getRemoteVersion'), array(), '', false); $loader->expects(self::once())->method('setRemoteFilename')->will(self::returnSelf()); $loader->expects(self::once())->method('setOptions')->will(self::returnSelf()); $loader->expects(self::once())->method('setLogger')->will(self::returnSelf()); $loader->expects(self::never())->method('load')->will(self::returnValue(false)); $loader->expects(self::once())->method('getRemoteVersion')->will(self::returnValue(6001)); $this->object->setLoader($loader); $map = array(array('browscap.time', false, null, null), array('browscap.version', false, null, 6000)); $cache = $this->getMock('\\BrowscapPHP\\Cache\\BrowscapCache', array('getItem', 'hasItem', 'setItem'), array(), '', false); $cache->expects(self::any())->method('getItem')->will(self::returnValueMap($map)); $cache->expects(self::any())->method('hasItem')->will(self::returnValue(true)); $cache->expects(self::never())->method('setItem')->will(self::returnValue(false)); $this->object->setCache($cache); self::assertSame(6000, $this->object->checkUpdate()); }
/** * @expectedException \BrowscapPHP\Exception\FetcherException * @expectedExceptionMessage Could not fetch HTTP resource "http://browscap.org/stream?q=PHP_BrowscapINI": */ public function testUpdate() { if (class_exists('\\Browscap\\Browscap')) { self::markTestSkipped('if the \\Browscap\\Browscap class is available the browscap.ini file is not updated from a remote ' . 'location'); } $logger = $this->getMock('\\Monolog\\Logger', array(), array(), '', false); $this->object->setLogger($logger); $loader = $this->getMock('\\BrowscapPHP\\Helper\\IniLoader', array('setRemoteFilename', 'setOptions', 'setLogger', 'load'), array(), '', false); $loader->expects(self::once())->method('setRemoteFilename')->will(self::returnSelf()); $loader->expects(self::once())->method('setOptions')->will(self::returnSelf()); $loader->expects(self::once())->method('setLogger')->will(self::returnSelf()); $loader->expects(self::once())->method('load')->will(self::returnValue(false)); $this->object->setLoader($loader); $this->object->setLoader($loader); $map = array(array('browscap.time', false, null, null), array('browscap.version', false, null, null)); $cache = $this->getMock('\\WurflCache\\Adapter\\Memory', array('getItem'), array(), '', false); $cache->expects(self::any())->method('getItem')->will(self::returnValueMap($map)); $this->object->setCache($cache); $this->object->update(); }
use BrowscapPHP\Browscap; use BrowscapPHP\Helper\IniLoader; use WurflCache\Adapter\File; /* * Browscap cache init */ include 'bootstrap.php'; /* * Full */ echo '.'; $cache = new File([File::DIR => '../myCache/.tmp/browscap/full']); $bc = new Browscap(); $bc->setCache($cache); $bc->convertFile('data/full_php_browscap.ini'); /* * Lite */ echo '.'; $cache = new File([File::DIR => '../myCache/.tmp/browscap/lite']); $bc = new Browscap(); $bc->setCache($cache); $bc->convertFile('data/lite_php_browscap.ini'); /* * PHP */ echo '.'; $cache = new File([File::DIR => '../myCache/.tmp/browscap/php']); $bc = new Browscap(); $bc->setCache($cache); $bc->convertFile('data/php_browscap.ini');
/** * Generate a build for build number specified * * @param string $buildNumber * @param \Composer\IO\IOInterface $io * @param bool $debug */ public static function createBuild($buildNumber, IOInterface $io = null, $debug = false) { $buildFolder = 'build/build-' . $buildNumber . '/'; $resourceFolder = 'vendor/browscap/browscap/resources/'; if (!file_exists($buildFolder)) { if ($io) { $io->write(' - Creating build folder'); } mkdir($buildFolder, 0775, true); } // Create a logger if ($io) { $io->write(' - Setting up logging'); } $loggerHelper = new LoggerHelper(); $logger = $loggerHelper->create($debug); $collectionCreator = new CollectionCreator(); if ($io) { $io->write(' - Creating writer collection'); } $writerCollectionFactory = new FullCollectionFactory(); $writerCollection = $writerCollectionFactory->createCollection($logger, $buildFolder); // Generate the actual browscap.ini files if ($io) { $io->write(' - Creating actual build'); } $buildGenerator = new BuildGenerator($resourceFolder, $buildFolder); $buildGenerator->setLogger($logger); $buildGenerator->setCollectionCreator($collectionCreator); $buildGenerator->setWriterCollection($writerCollection); $buildGenerator->run($buildNumber, false); if ($io) { $io->write(' - Creating cache'); } $iniFile = $buildFolder . 'full_php_browscap.ini'; $cache = new File(array(File::DIR => 'cache/')); $browscap = new Browscap(); $browscap->setCache($cache)->setLogger($logger); $browscap->convertFile($iniFile); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $loggerHelper = new LoggerHelper(); $logger = $loggerHelper->create($input->getOption('debug')); $browscap = new Browscap(); $browscap->setLogger($logger)->setCache($this->getCache($input)); $result = $browscap->getBrowser($input->getArgument('user-agent')); if (!defined('JSON_PRETTY_PRINT')) { // not defined in PHP 5.3 define('JSON_PRETTY_PRINT', 128); } $output->writeln(json_encode($result, JSON_PRETTY_PRINT)); }
/** * @param \Symfony\Component\Console\Output\OutputInterface $output * @param \BrowscapPHP\Util\Logfile\ReaderCollection $collection * @param \BrowscapPHP\Browscap $browscap * @param int $line * * @throws UnknownBrowserException * @throws UnknownBrowserTypeException * @throws UnknownDeviceException * @throws UnknownEngineException * @throws UnknownPlatformException * @throws \Exception */ private function handleLine(OutputInterface $output, ReaderCollection $collection, Browscap $browscap, $line) { $userAgentString = ''; try { $userAgentString = $collection->read($line); try { $this->getResult($browscap->getBrowser($userAgentString)); } catch (\Exception $e) { $this->undefinedClients[] = $userAgentString; throw $e; } $type = '.'; ++$this->countOk; } catch (ReaderException $e) { $type = 'E'; ++$this->countNok; } catch (UnknownBrowserTypeException $e) { $type = 'T'; ++$this->countNok; } catch (UnknownBrowserException $e) { $type = 'B'; ++$this->countNok; } catch (UnknownPlatformException $e) { $type = 'P'; ++$this->countNok; } catch (UnknownDeviceException $e) { $type = 'D'; ++$this->countNok; } catch (UnknownEngineException $e) { $type = 'N'; ++$this->countNok; } catch (\Exception $e) { $type = 'U'; ++$this->countNok; } $this->outputProgress($output, $type); // count all useragents if (isset($this->uas[$userAgentString])) { ++$this->uas[$userAgentString]; } else { $this->uas[$userAgentString] = 1; } if ('.' !== $type && 'E' !== $type) { // count all undetected useragents grouped by detection error if (!isset($this->uasWithType[$type])) { $this->uasWithType[$type] = []; } if (isset($this->uasWithType[$type][$userAgentString])) { ++$this->uasWithType[$type][$userAgentString]; } else { $this->uasWithType[$type][$userAgentString] = 1; } } }
/** * Display the sessions and logs informations. * * @return void */ public function security() { $records = $this->SessionsActivity->getOnlineSessionsForUser($this->Auth->user('id')); $browscap = new Browscap(); $sessions = []; foreach ($records as $record) { $infos = $browscap->getBrowser($record->user_agent); $record->infos = $infos; array_push($sessions, $record); } $this->loadModel('UsersLogs'); $this->paginate = ['maxLimit' => 25]; $logs = $this->UsersLogs->find()->where(['UsersLogs.user_id' => $this->Auth->user('id')])->order(['UsersLogs.created' => 'DESC'])->formatResults(function ($logs) use($browscap) { return $logs->map(function ($log) use($browscap) { $log->infos = $browscap->getBrowser($log->user_agent); return $log; }); }); $logs = $this->paginate($logs); $user = $this->Users->find()->where(['Users.id' => $this->Auth->user('id')])->select(['id', 'two_factor_auth_enabled'])->first(); $this->set(compact('sessions', 'logs', 'user')); }