11<?php
22namespace vipnytt ;
33
4- use Exception ;
4+ use vipnytt \ UserAgentParser \ Exceptions \ FormatException ;
55
66/**
77 * Class UserAgentParser
@@ -17,29 +17,46 @@ class UserAgentParser
1717 * Constructor
1818 *
1919 * @param string $userAgent
20- * @throws Exception
2120 */
2221 public function __construct ($ userAgent )
2322 {
2423 mb_detect_encoding ($ userAgent );
25- $ this ->userAgent = mb_strtolower (trim ($ userAgent ));
24+ $ this ->userAgent = trim ($ userAgent );
25+ $ this ->checkFormat ();
2626 $ this ->explode ();
2727 }
2828
29+ /**
30+ * Validate the UserAgent format
31+ *
32+ * @throws FormatException
33+ */
34+ protected function checkFormat ()
35+ {
36+ if (preg_match ('/\s/ ' , $ this ->userAgent )) {
37+ throw new FormatException ("Format not supported. Please use `name/version` or just `name`, eg. `MyUserAgent/1.0` and `MyUserAgent`. " );
38+ }
39+ }
40+
2941 /**
3042 * Parses all possible User-Agent groups to an array
3143 *
3244 * @return array
3345 */
3446 private function explode ()
3547 {
36- $ this ->groups = [$ this ->userAgent ];
37- $ this ->groups [] = $ this ->stripVersion ();
38- while (mb_strpos (end ($ this ->groups ), '- ' ) !== false ) {
39- $ current = end ($ this ->groups );
40- $ this ->groups [] = mb_substr ($ current , 0 , mb_strrpos ($ current , '- ' ));
48+ $ groups = [$ this ->userAgent ];
49+
50+ $ groups [] = $ this ->stripVersion ();
51+ while (mb_stripos (end ($ groups ), '- ' ) !== false ) {
52+ $ current = end ($ groups );
53+ $ groups [] = mb_substr ($ current , 0 , mb_strripos ($ current , '- ' ));
54+ }
55+ foreach ($ groups as $ group ) {
56+ if (!in_array ($ group , $ this ->groups )) {
57+ $ this ->groups [] = $ group ;
58+ }
4159 }
42- $ this ->groups = array_unique ($ this ->groups );
4360 }
4461
4562 /**
@@ -49,7 +66,7 @@ private function explode()
4966 */
5067 public function stripVersion ()
5168 {
52- if (mb_strpos ($ this ->userAgent , '/ ' ) !== false ) {
69+ if (mb_stripos ($ this ->userAgent , '/ ' ) !== false ) {
5370 return mb_split ('/ ' , $ this ->userAgent , 2 )[0 ];
5471 }
5572 return $ this ->userAgent ;
@@ -64,8 +81,9 @@ public function stripVersion()
6481 */
6582 public function match ($ array )
6683 {
84+ $ array = array_map ('mb_strtolower ' , $ array );
6785 foreach ($ this ->groups as $ userAgent ) {
68- if (in_array ($ userAgent, array_map ( ' mb_strtolower ' , $ array) )) {
86+ if (in_array (mb_strtolower ( $ userAgent), $ array )) {
6987 return $ userAgent ;
7088 }
7189 }
0 commit comments