24 use Wikimedia\AtEase\AtEase;
48 private $timeout = 30;
60 private $options = [];
65 private $requestFactory;
72 $this->endpoint = $url;
73 $this->requestFactory = $requestFactory;
74 $this->userAgent = $requestFactory->
getUserAgent() .
" SparqlClient";
83 if ( $timeout >= 0 ) {
84 $this->timeout = $timeout;
94 $this->options = $options;
103 return $this->userAgent;
114 $this->userAgent = $agent;
127 $this->userAgent .=
' ' . $agent;
140 public function query( $sparql, $rawData =
false ) {
141 if ( empty( $this->endpoint ) ) {
144 $queryData = [
"query" => $sparql,
"format" =>
"json" ];
145 $options = array_merge( [
'method' =>
'GET' ], $this->options );
147 if ( empty( $options[
'userAgent'] ) ) {
148 $options[
'userAgent'] = $this->userAgent;
151 if ( $this->timeout >= 0 ) {
153 $queryData[
'maxQueryTimeMillis'] = $this->timeout * 1000;
154 $options[
'timeout'] = $this->timeout;
157 if ( strlen( $sparql ) > self::MAX_GET_SIZE ) {
159 $options[
'method'] =
'POST';
160 $options[
'postData'] =
'query=' . urlencode( $sparql );
161 unset( $queryData[
'query'] );
165 $request = $this->requestFactory->create( $url, $options, __METHOD__ );
167 $status = $request->execute();
169 if ( !$status->isOK() ) {
170 throw new SparqlException(
'HTTP error: ' . $status->getWikiText(
false,
false,
'en' ) );
172 $result = $request->getContent();
173 AtEase::suppressWarnings();
174 $data = json_decode( $result,
true );
175 AtEase::restoreWarnings();
176 if ( $data ===
null || $data ===
false ) {
178 substr( $result, 1024 ) );
181 return $this->extractData( $data, $rawData );
194 private function extractData( $data, $rawData =
false ) {
196 if ( $data && !empty( $data[
'results'] ) ) {
197 $vars = $data[
'head'][
'vars'];
199 foreach ( $data[
'results'][
'bindings'] as $row ) {
200 foreach ( $vars as $var ) {
201 if ( !isset( $row[$var] ) ) {
202 $resrow[$var] =
null;
206 $resrow[$var] = $row[$var];
208 $resrow[$var] = $row[$var][
'value'];
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...