1+ <?php
2+
3+ /**
4+ * get the full name (name \ namespace) of a class from its file path
5+ * result example: (string) "I\Am\The\Namespace\Of\This\Class"
6+ *
7+ * @param $filePathName
8+ *
9+ * @return string
10+ */
11+ function getClassFullNameFromFile ($ filePathName )
12+ {
13+ return $ this ->getClassNamespaceFromFile ($ filePathName ) . '\\' . $ this ->getClassNameFromFile ($ filePathName );
14+ }
15+
16+
17+ /**
18+ * build and return an object of a class from its file path
19+ *
20+ * @param $filePathName
21+ *
22+ * @return mixed
23+ */
24+ function getClassObjectFromFile ($ filePathName )
25+ {
26+ $ classString = $ this ->getClassFullNameFromFile ($ filePathName );
27+
28+ $ object = new $ classString ;
29+
30+ return $ object ;
31+ }
32+
33+
34+ /**
35+ * get the class namespace form file path using token
36+ *
37+ * @param $filePathName
38+ *
39+ * @return null|string
40+ */
41+ function getClassNamespaceFromFile ($ filePathName )
42+ {
43+ $ src = file_get_contents ($ filePathName );
44+
45+ $ tokens = token_get_all ($ src );
46+ $ count = count ($ tokens );
47+ $ i = 0 ;
48+ $ namespace = '' ;
49+ $ namespace_ok = false ;
50+ while ($ i < $ count ) {
51+ $ token = $ tokens [$ i ];
52+ if (is_array ($ token ) && $ token [0 ] === T_NAMESPACE ) {
53+ // Found namespace declaration
54+ while (++$ i < $ count ) {
55+ if ($ tokens [$ i ] === '; ' ) {
56+ $ namespace_ok = true ;
57+ $ namespace = trim ($ namespace );
58+ break ;
59+ }
60+ $ namespace .= is_array ($ tokens [$ i ]) ? $ tokens [$ i ][1 ] : $ tokens [$ i ];
61+ }
62+ break ;
63+ }
64+ $ i ++;
65+ }
66+ if (!$ namespace_ok ) {
67+ return null ;
68+ } else {
69+ return $ namespace ;
70+ }
71+ }
72+
73+ /**
74+ * get the class name form file path using token
75+ *
76+ * @param $filePathName
77+ *
78+ * @return mixed
79+ */
80+ function getClassNameFromFile ($ filePathName )
81+ {
82+ $ php_code = file_get_contents ($ filePathName );
83+
84+ $ classes = array ();
85+ $ tokens = token_get_all ($ php_code );
86+ $ count = count ($ tokens );
87+ for ($ i = 2 ; $ i < $ count ; $ i ++) {
88+ if ($ tokens [$ i - 2 ][0 ] == T_CLASS
89+ && $ tokens [$ i - 1 ][0 ] == T_WHITESPACE
90+ && $ tokens [$ i ][0 ] == T_STRING
91+ ) {
92+
93+ $ class_name = $ tokens [$ i ][1 ];
94+ $ classes [] = $ class_name ;
95+ }
96+ }
97+
98+ return $ classes [0 ];
99+ }
0 commit comments