Skip to content

Commit 5701c27

Browse files
committed
Added testGenerateEventUrl and refactored code for readability.
1 parent 8eb13c9 commit 5701c27

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

src/Proxy.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,7 @@ public function do_request( $name = 'pageview', $domain = '', $url = '', $props
114114

115115
// URL is required, so if no $url was set and no referer was found, attempt to create it from the REQUEST_URI server variable.
116116
if ( empty( $body[ 'u' ] ) ) {
117-
$parts = parse_url( $_SERVER[ 'REQUEST_URI' ] );
118-
$home_url_parts = parse_url( get_home_url() );
119-
120-
if ( isset( $home_url_parts[ 'scheme' ] ) && isset( $home_url_parts[ 'host' ] ) && isset( $parts[ 'path' ] ) ) {
121-
$body[ 'u' ] = $home_url_parts[ 'scheme' ] . '://' . $home_url_parts [ 'host' ] . $parts[ 'path' ];
122-
}
117+
$body[ 'u' ] = $this->generate_event_url(); // @codeCoverageIgnore
123118
}
124119

125120
// Revenue events use a different approach.
@@ -134,6 +129,23 @@ public function do_request( $name = 'pageview', $domain = '', $url = '', $props
134129
return $this->send_event( $request );
135130
}
136131

132+
/**
133+
* Attempts to generate the Event URL from available resources.
134+
*
135+
* @return string
136+
*/
137+
public function generate_event_url() {
138+
$url = '';
139+
$parts = parse_url( $_SERVER[ 'REQUEST_URI' ] );
140+
$home_url_parts = parse_url( get_home_url() );
141+
142+
if ( isset( $home_url_parts[ 'scheme' ] ) && isset( $home_url_parts[ 'host' ] ) && isset( $parts[ 'path' ] ) ) {
143+
$url = $home_url_parts[ 'scheme' ] . '://' . $home_url_parts [ 'host' ] . $parts[ 'path' ];
144+
}
145+
146+
return $url;
147+
}
148+
137149
/**
138150
* Formats and sends $request to the Plausible API.
139151
*

tests/integration/ProxyTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
/**
3+
* @package Plausible Analytics Unit Tests - ClientFactory
4+
*/
5+
6+
namespace Plausible\Analytics\Tests\Integration;
7+
8+
use Plausible\Analytics\Tests\TestCase;
9+
use Plausible\Analytics\WP\Proxy;
10+
11+
class ProxyTest extends TestCase {
12+
/**
13+
* @see Proxy::generate_event_url()
14+
* @return void
15+
*/
16+
public function testGenerateEventUrl() {
17+
$proxy = new Proxy( false );
18+
19+
$url = $proxy->generate_event_url();
20+
21+
$this->assertEquals( 'http://example.org', $url );
22+
23+
$_SERVER[ 'REQUEST_URI' ] = '/test';
24+
25+
$url = $proxy->generate_event_url();
26+
27+
$this->assertEquals( 'http://example.org/test', $url );
28+
}
29+
}

0 commit comments

Comments
 (0)