PK ?VN phpunit.xml.distnu W+A
tests
tests/Elasticsearch/Tests/YamlRunnerTest.php
src
PK ?V phpunit-integration.xmlnu W+A
tests/Elasticsearch/Tests/YamlRunnerTest.php
src
PK ?VZn n LICENSEnu W+A
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
PK ?VDZI .travis.ymlnu W+A language: php
services:
- docker
branches:
except:
- 0.4
sudo: true
matrix:
fast_finish: true
include:
- php: 7.0
env: ES_VERSION="6.7.0"
- php: 7.1
env: ES_VERSION="6.7.0"
- php: 7.2
env: ES_VERSION="6.7.0"
- php: 7.3
env: ES_VERSION="6.0.0"
- php: 7.3
env: ES_VERSION="6.1.0"
- php: 7.3
env: ES_VERSION="6.2.0"
- php: 7.3
env: ES_VERSION="6.3.0"
- php: 7.3
env: ES_VERSION="6.4.0"
- php: 7.3
env: ES_VERSION="6.5.0"
- php: 7.3
env: ES_VERSION="6.6.0"
- php: 7.3
env: ES_VERSION="6.7.0"
env:
global:
- ES_TEST_HOST=http://localhost:9200
before_install:
- ./travis/run_es_docker.sh
install:
- composer install --prefer-dist
before_script:
- if [ $TRAVIS_PHP_VERSION = '7.3' ]; then PHPUNIT_FLAGS="--coverage-clover ./build/logs/clover.xml"; fi
- php util/RestSpecRunner.php
- php util/EnsureClusterAlive.php
script:
- if [ $TRAVIS_PHP_VERSION != '7.3' ]; then composer run-script phpcs; fi
- composer run-script phpstan
- vendor/bin/phpunit $PHPUNIT_FLAGS
- vendor/bin/phpunit -c phpunit-integration.xml --group sync $PHPUNIT_FLAGS
after_script:
- if [ $TRAVIS_PHP_VERSION = '7.3' ]; then php vendor/bin/coveralls; fi
notifications:
email: true
PK ?VDe ( ( .php_csnu W+A exclude('benchmarks')
->exclude('docs')
->exclude('util')
->exclude('.github')
->exclude('util')
->exclude('travis')
->exclude('util/cache')
->exclude('util/elasticsearch')
->exclude('vendor')
->in(__DIR__);
return Symfony\CS\Config\Config::create()
->setUsingCache(true)
->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
->finder($finder);
}
return php_cs();
PK ?V| BREAKING_CHANGES.mdnu W+A # 6.7
- `{type}` part in `indices.put_mapping` API is not required anymore, see new specification [here](https://github.com/elastic/elasticsearch/blob/v6.7.0/rest-api-spec/src/main/resources/rest-api-spec/api/indices.put_mapping.json)
# 6.0
- [Search Templates]: PutTemplate endpoint has been removed (see [Elasticsearch Breaking Changes](https://www.elastic.co/guide/en/elasticsearch/reference/current/breaking_60_scripting_changes.html#_stored_search_template_apis_removed)),
use PutScript instead.
- [#674](https://github.com/elastic/elasticsearch-php/pull/674) `ClientBuilder::defaultLogger()` method was removed. It is recommended to [create the logger object manually](https://github.com/elastic/elasticsearch-php/blob/master/docs/configuration.asciidoc#enabling-the-logger).
PK ?Vܴ .github/CONTRIBUTING.mdnu W+A If you have a bugfix or new feature that you would like to contribute to elasticsearch-php, please find or open an issue about it first. Talk about what you would like to do. It may be that somebody is already working on it, or that there are particular issues that you should know about before implementing the change.
We enjoy working with contributors to get their code accepted. There are many approaches to fixing a problem and it is important to find the best approach before writing too much code.
The process for contributing to any of the Elasticsearch repositories is similar.
1. Sign the contributor license agreement
Please make sure you have signed the [Contributor License Agreement](https://www.elastic.co/contributor-agreement/). We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once.
2. Set up your fork for development
$> git clone https://github.com/elasticsearch/elasticsearch-php.git
$> cd elasticsearch-php
$> git submodule update --init --recursive
$> curl -s http://getcomposer.org/installer | php
$> php composer.phar install --dev
3. Ensure a version of Elasticsearch is running on your machine. Recommended "test" configuration is:
$> bin/elasticsearch -Des.gateway.type=none -Des.http.port=9200 \
-Des.index.store.type=memory -Des.discovery.zen.ping.multicast.enabled=false \
-Des.node.bench=true -Des.script.disable_dynamic=false
4. Run the unit and yaml integration tests to ensure your changes do not break existing code. The `util/RestSpecRunner.php` script will automatically checkout the tests for the exact same build as is the Elasticsearch you are running on your machine (since tests are specific to the server version):
$> export ES_TEST_HOST='http://localhost:9200'
Then proceed to initialize the REST yaml tests and run the package. **WARNING: the unit tests will clear your cluster
and data..._do not_ run the tests on a production cluster!**
$> php util/RestSpecRunner.php
$> php vendor/bin/phpunit
5. Ensure your changes follow the [PSR-2 Coding Style Guide](http://www.php-fig.org/psr/psr-2/). You can run tools such as [PHP-CS-Fixer](http://cs.sensiolabs.org/) or [PHP_CodeSniffer](http://pear.php.net/package/PHP_CodeSniffer) to enforce PSR-2 automatically.
6. Rebase your changes
Update your local repository with the most recent code from the main elasticsearch-php repository, and rebase your branch on top of the latest master branch. We prefer your changes to be squashed into a single commit.
7. Submit a pull request
Push your local changes to your forked copy of the repository and submit a pull request. In the pull request, describe what your changes do and mention the number of the issue where discussion has taken place, eg “Closes #123″. Please consider adding or modifying tests related to your changes.
Then sit back and wait. There will probably be discussion about the pull request and, if any changes are needed, we would love to work with you to get your pull request merged into elasticsearch-php.
PK ?V6(9 9 .github/ISSUE_TEMPLATE.mdnu W+A
### Summary of problem or feature request
### Code snippet of problem
### System details
- Operating System
- PHP Version
- ES-PHP client version
- Elasticsearch versionPK ?VR .github/PULL_REQUEST_TEMPLATE.mdnu W+A
PK ?V-F phpstan-tests.neonnu W+A parameters:
ignoreErrors:
- '#Mockery\\MockInterface::shouldReceive\(\)#'
- '#Mockery\\MockInterface given#'
# because of \Elasticsearch\Tests\RegisteredNamespaceTest
- '#Call to an undefined method Elasticsearch\\Client::foo\(\)#'
- '#Call to an undefined method Elasticsearch\\Client::bar\(\)#'
# because of \Elasticsearch\Tests\ClientBuilderTest
- '#expects Psr\\Log\\LoggerInterface, Elasticsearch\\Tests\\ClientBuilder\\DummyLogger given.$#'
# probably PHPStan issue, because it actually works https://3v4l.org/s3U2B
- '#Argument of an invalid type array\|stdClass supplied for foreach, only iterables are supported#'
PK ?VZM util/docstheme/manifest.ymlnu W+A name: asciidoc
global:
"pages/namespaces.twig": "namespaces.asciidoc"
"pages/interfaces.twig": "interfaces.asciidoc"
"pages/classes.twig": "classes.asciidoc"
class:
"pages/class.twig": "%s.asciidoc"
PK ?V3IGB B util/docstheme/layout/base.twignu W+A {% from "macros.twig" import replace_backslash, sanitize %}
{% block title %}
{% set parts = title|split("\\") %}
{% set path = parts|slice(0, -1)|join("\\") %}
{% set name = parts|slice(-1, 1)|join("\\") %}
[[{{ sanitize(replace_backslash(title)) }}]]
=== {{ title }}
{% endblock %}
{% block content %}
{% endblock %}
PK ?V$ util/docstheme/macros.twignu W+A {% macro class_item(class, short = false, indent = "") -%}
{{ indent }}{{ _self.class_name(class, short) }}{% if class.shortdesc %} -- {{ class.shortdesc }}{% endif %}
{%- endmacro -%}
{% macro class_name(class, short = false, suffix = "") -%}
{% spaceless -%}
{% if class.projectclass or class.phpclass %}
{% if class.projectclass %}
<<{{_self.replace_backslash( (short ? class.shortname : class)~suffix) }},{{ class }}>>
{% else %}
http://php.net/class.{{ class }}[{{ short ? class.shortname : class }}{{ suffix }}]
{% endif %})
{% else %}
`{{ class }}`
{% endif %}
{%- endspaceless %}
{%- endmacro -%}
{% macro class_type(class, sentence = false) -%}
{% spaceless %}
{% if class.interface %}
{% if sentence %}an {% endif %}
interface
{%- else -%}
{% if sentence %}{% if class.abstract %}an{% else %}a{% endif %} {% endif %}
{% if class.abstract %}abstract {% endif %}
class
{%- endif -%}
{% endspaceless %}
{%- endmacro -%}
{% macro hint(hint) -%}
{% spaceless %}
{% if hint.class -%}
{{ _self.class_name(hint.name) }}
{%- elseif hint.name -%}
{{ hint.name }}
{%- endif %}
{% endspaceless %}
{%- endmacro -%}
{% macro markdown_path(path) -%}
{% spaceless %}
{{- path|replace({".html": ".md"}) -}}
{% endspaceless %}
{%- endmacro -%}
{% macro replace_backslash(path) -%}
{% spaceless %}
{{- path|replace({"\\": "_"}) -}}
{% endspaceless %}
{%- endmacro -%}
{% macro back_to_forward(path) -%}
{% spaceless %}
{{- path|replace({"\\": "/"}) -}}
{% endspaceless %}
{%- endmacro -%}
{% macro sanitize(path) -%}
{% spaceless %}
{{- path|replace({"$": "", "::": "", "__": "-"}) -}}
{% endspaceless %}
{%- endmacro -%}
{% macro get_namespace(class) -%}
{% spaceless %}
{% if class.shortname == 'Client' %}
$client
{% else %}
$client->{{ class.shortname|lower|replace({"namespace": ""}) }}()
{% endif %}
{% endspaceless %}
{%- endmacro -%}
{% macro param_list(member) -%}
{% spaceless %}
{% for parameter in member.parameters %}${{ parameter.name }},{% endfor %}
{% endspaceless %}
{%- endmacro -%}
{% macro member_signature(type, member) -%}
* It is a **{{ _self.member_visibility(member) }}{% if member.abstract is defined and member.abstract %} abstract{% endif %}** {{ type }}.
{% if member.final %}
* It is a **finalized** {{ type }}.
{% endif %}
{% if "property" == type %}
{% if member.hint|length > 1 %}
* It can be one of the following types:
{%- for hint in member.hint %}
* {{ _self.hint(hint) }}
{%- endfor -%}
{%- elseif member.hint|length > 0 %}
* It is a(n) {{ _self.hint(member.hint[0]) }} value.
{%- else %}
* Its type is not specified.
{% endif %}
{% elseif "method" == type %}
{% if member.parameters %}
* It accepts the following parameter(s):
{% for parameter in member.parameters %}
* `${{ parameter.name }}`{% if parameter.hint %} ({% for hint in parameter.hint %}{{ _self.hint(hint) }}{% if not loop.last %}|{% endif %}{% endfor %}){% endif %}{% if parameter.shortdesc %} -- {{ parameter.shortdesc }}{% endif %}
{% endfor %}
{% endif %}
{% if (member.hint|length > 1) or member.hintDesc %}
{% if member.hintDesc %}
* _Returns:_ {{ member.hintDesc }}
{% else %}
* It can return one of the following values:
{% endif %}
{% for hint in member.hint %}
* {{ _self.hint(hint) }}
{% endfor -%}
{% elseif member.hint|length > 0 %}
* It returns a(n) {{ _self.hint(member.hint[0]) }} value.
{% else %}
* It does not return anything.
{% endif %}
{% if member.exceptions %}
* It throws one of the following exceptions:
{% for exception in member.exceptions %}
* {{ _self.class_name(exception[0]) }}{% if exception[1] is defined and exception[1] is not empty %} -- {{ exception[1] }}{% endif %}
{% endfor %}
{% endif %}
{% endif %}
{%- endmacro -%}
{% macro member_visibility(member) -%}
{% spaceless %}
{% if member.private %}private{% elseif member.protected %}protected{% else %}public{% endif %}
{% if member.static %} static{% endif %}
{% endspaceless %}
{%- endmacro -%}
PK ?Vܷ ! util/docstheme/pages/classes.twignu W+A {% extends "layout/base.twig" %}
{% from "macros.twig" import class_item, replace_backslash, back_to_forward, sanitize %}
{% block title %}
[[{{ sanitize(replace_backslash("ElasticsearchPHP_Endpoints")) }}]]
== {{ "Reference - Endpoints" }}
{% endblock %}
{% block content %}
This is a complete list of namespaces and their associated endpoints.
NOTE: This is auto-generated documentation
{% for class in classes if not class.interface %}
* <<{{ replace_backslash(class) }}, {{ class }}>>
{% else %}
* There are no endpoints available.
{% endfor %}
{% for class in classes if not class.interface %}
include::{{ back_to_forward(class) }}.asciidoc[]
{% else %}
{% endfor %}
{% endblock %}
PK ?Vcc܋ $ util/docstheme/pages/interfaces.twignu W+A {% extends "layout/base.twig" %}
{% from "macros.twig" import class_item, replace_backslash, back_to_forward, sanitize %}
{% block title %}
[[{{ sanitize(replace_backslash("ElasticsearchPHP_Interfaces")) }}]]
== {{ "Reference - Interfaces" }}
{% endblock %}
{% block content %}
This is a complete list of available interfaces:
{% for interface in classes if interface.interface %}
* <<{{ replace_backslash(interface) }}, {{ interface }}>>
{% else %}
* There are no interfaces available.
{% endfor %}
{% for interface in classes if interface.interface %}
include::{{ back_to_forward(interface) }}.asciidoc[]
{% else %}
{% endfor %}
{% endblock %}
PK ?V]Mf f $ util/docstheme/pages/namespaces.twignu W+A {% extends "layout/base.twig" %}
{% from "macros.twig" import markdown_path, replace_backslash, back_to_forward, sanitize %}
{% block title %}
[[{{ sanitize(replace_backslash("ElasticsearchPHP_Namespaces")) }}]]
== {{ "Reference - Namespaces" }}
{% endblock %}
{% block content %}
This is a complete list of available namespaces:
{% for namespace in namespaces %}
* <<{{ replace_backslash(namespace) }}, {{ namespace }}>>
{% else %}
* There are no namespaces available.
{% endfor %}
{% for namespace in namespaces %}
include::{{ back_to_forward(namespace) }}.asciidoc[]
{% else %}
{% endfor %}
{% endblock %}
PK ?Vm!u util/docstheme/pages/class.twignu W+A {% extends "layout/base.twig" %}
{% from "macros.twig" import class_item, class_name, class_type, member_signature, replace_backslash, sanitize, param_list, get_namespace %}
{% block title %}
{% set title = class %}
{{ parent() }}
{% endblock %}
{% block content %}
{% if class.shortdesc %}
{{ class.shortdesc|raw }}
{% endif %}
{% if class.longdesc %}
*Description*
{{ class.longdesc|raw }}
{% endif %}
{% if class.methods %}
*Methods*
The {{ class_type(class) }} defines the following methods:
{% for method in class.methods %}
{% if method.name != "__construct" %}
* <<{{ sanitize(replace_backslash(method)~"_"~method.name) }},`{{ method.name }}()`>>
{% endif %}
{% endfor %}
{% for method in class.methods %}
{% if method.name != "__construct" %}
{% if class.shortname != "ClientBuilder" %}
[[{{ sanitize(replace_backslash(method)~"_"~method.name) }}]]
.`{{ method.name }}()`
****
[source,php]
----
/*
{% if method.shortdesc %}
{{ method.shortdesc|raw }}
['body'] = (array) Request body
{% endif %}
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = {{ get_namespace(class) }}->{{ method.name }}({{ param_list(method)|trim(',') }});
----
****
{% else %}
[[{{ sanitize(replace_backslash(method)~"_"~method.name) }}]]
.`{{ method.name }}()`
****
[source,php]
----
/*
{% if method.shortdesc %}
{{ method.shortdesc|raw }}
['body'] = (array) Request body
{% endif %}
*/
----
****
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
{% endblock %}
PK ?Vd* util/RestSpecRunner.phpnu W+A [$_SERVER['ES_TEST_HOST']]
]);
$serverInfo = $client->info();
var_dump($serverInfo);
$gitWrapper = new \GitWrapper\GitWrapper();
echo "Git cwd: ".dirname(__DIR__) . "/util/elasticsearch\n";
$git = $gitWrapper->workingCopy(dirname(__DIR__) . '/util/elasticsearch');
echo "Update elasticsearch submodule\n";
$git->fetchAll(array('verbose' => true));
$hash = $serverInfo['version']['build_hash'];
echo "Checkout yaml tests (hash: $hash)\n";
$git->checkout($hash, array('force' => true, 'quiet' => true));
PK ?V G util/SpecParser.phpnu W+A #!/usr/bin/env php
loadTemplate('endpoint.twig');
$counter = 0;
function getApiPath()
{
$path = dirname(__FILE__).'/elasticsearch/rest-api-spec/api';
if (file_exists($path) !== true) {
$path = dirname(__FILE__).'/elasticsearch/rest-api-spec/src/main/resources/rest-api-spec/api';
}
return $path;
}
if ($handle = opendir(getApiPath())) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
generateTemplate($entry, $template);
}
}
closedir($handle);
}
function processURLPaths($data)
{
$final = array();
$containsType = false;
$containsIndex = false;
foreach ($data['url']['paths'] as $path) {
$params = array();
preg_match_all('/{(.*?)}/', $path, $params);
$params = $params[1];
$count = count($params);
$parsedPath = str_replace('}', '', $path);
$parsedPath = str_replace('{', '$', $parsedPath);
if (array_search('index', $params) !== false) {
$containsIndex = true;
}
if (array_search('type', $params) !== false) {
$containsType = true;
}
$duplicate = false;
foreach ($final as $existing) {
if ($existing['params'] === $params) {
$duplicate = true;
}
}
if ($duplicate !== true) {
$final[] = array(
'path' => $path,
'parsedPath' => $parsedPath,
'params' => $params,
'count' => $count
);
}
}
/*
foreach ($final as &$existing) {
if ($containsIndex === true && array_search('index', $existing['params']) === false && array_search('type', $existing['params']) !== false) {
$existing['parsedPath'] = '/_all'.$existing['parsedPath'];
}
}
*/
usort($final, function ($a, $b) {
if ($a['count'] == $b['count']) {
return 0;
}
return ($a['count'] > $b['count']) ? -1 : 1;
});
return $final;
}
function getDefaultPath($path)
{
if ($path['count'] === 0) {
return $path['path'];
} else {
$final = str_replace('}', '', $path['path']);
$final = str_replace('{', '$', $final);
return $final;
}
}
function forbid($key, $value)
{
$forbid = array(
'GET' => array(
'/_nodes/hotthreads',
'/_nodes/{node_id}/hotthreads',
'/_nodes/{metric}'
),
'HEAD' => array(),
'PUT' => array(
'/{index}/{type}/_mapping'
),
'POST' => array(
'/_all/{type}/_bulk',
'/_all/{type}/_mget'
),
'DELETE' => array(
'/{index}/{type}',
'/{index}/{type}/_mapping'
),
'QS' => array(
'operation_threading',
'field_data'
)
);
if (isset($forbid['key']) && $forbid['key'] === $value) {
return true;
} else {
return false;
}
}
function generateTemplate($path, $template)
{
$ignoreList = array(
'index.json', 'bulk.json'
);
if (array_search($path, $ignoreList) !== false) {
return;
}
$path = getApiPath().DIRECTORY_SEPARATOR.$path;
$json = file_get_contents($path);
$data = json_decode($json, true);
reset($data);
$namespace = key($data);
$data = $data[$namespace];
$namespace = explode('.', $namespace);
$underscoreNamespace = array(
'get',
'put',
'post',
'delete',
'exists',
'update',
'create'
);
$exceptions = array(
'delete_by_query',
'update_by_query',
);
if (strpos($namespace[count($namespace)-1], '_')) {
$temp = explode('_', $namespace[count($namespace)-1]);
if (array_search($temp[0], $underscoreNamespace) !== false && array_search($namespace[count($namespace)-1], $exceptions) === false) {
$namespace[count($namespace)-1] = $temp[1];
$namespace[] = $temp[0];
} else {
$namespace[count($namespace)-1] = str_replace('_', '', $namespace[count($namespace)-1]);
}
}
$data['url']['processed'] = processURLPaths($data);
$data['url']['default'] = getDefaultPath($data['url']['processed'][count($data['url']['processed'])-1]);
if (count($data['methods']) > 1) {
if (in_array("GET", $data['methods'])) {
$data['methods'] = "GET";
} else {
$data['methods'] = $data['methods'][0];
}
}
$renderVars = array(
'json' => $json,
'data' => $data,
'namespace' => $namespace,
'className' => ucfirst($namespace[count($namespace)-1]),
);
$ret = $template->render($renderVars);
$dir = __DIR__.'/output/'.implode('/', array_map('ucfirst', array_splice($namespace, 0, count($namespace)-1)));
if (substr($dir, -1) !== '/') {
$dir .= '/';
}
if (!file_exists($dir)) {
echo 'making dir: '.$dir."\n\n";
$oldumask = umask(0);
mkdir($dir, 0777, true);
umask($oldumask);
}
echo $dir."\n\n";
$path = $dir.$renderVars['className'].'.php';
echo $path."\n\n";
file_put_contents($path, $ret);
}
PK ?V0= = util/docsConfig.phpnu W+A files()
->name('*Namespace.php')
->name("Client.php")
->name("ClientBuilder.php")
->notName("AbstractNamespace.php")
->in(__DIR__.'/../src/');
return new Sami($iterator, [
'theme' => 'asciidoc',
'template_dirs' => [__DIR__.'/docstheme/'],
'title' => 'Elasticsearch-php',
'build_dir' => __DIR__.'/../docs/build',
'cache_dir' => __DIR__.'/cache/',
]);
PK ?V(R{ { util/EnsureClusterAlive.phpnu W+A [$_SERVER['ES_TEST_HOST']]
]);
$count = 0;
while (!$client->ping()) {
$count += 1;
if ($count > 15) {
echo "Live cluster could not be found in 15s!\nContents of elasticsearch.log:\n\n";
$dir = new DirectoryIterator(dirname(__DIR__));
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
if (strpos($fileinfo->getFilename(), "elasticsearch") === 0) {
$log = file_get_contents(dirname(__DIR__)."/$fileinfo/logs/elasticsearch.log");
echo $log;
break;
}
}
}
throw new \Exception();
}
sleep(1);
}
PK ?Vr+ util/templates/endpoint.twignu W+A
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elastic.co
*/
class {{ className|title }} extends AbstractEndpoint
{
{% for part, info in data.url.parts %}
{% if part != 'index' and part != 'type' and part != 'id' %}
// {{info.description }}
private ${{part}};
{% endif %}
{% endfor %}
{% if data.body is not null %}
/**
* @param array $body
*
* @throws \Elasticsearch\Common\Exceptions\InvalidArgumentException
* @return $this
*/
public function setBody($body)
{
if (isset($body) !== true) {
return $this;
}
$this->body = $body;
return $this;
}
{% endif %}
{% for part, info in data.url.parts %}
{% if part != 'index' and part != 'type' and part != 'id' %}
/**
* @param ${{part}}
*
* @return $this
*/
public function set{{part|title|replace({'_': ""})}}(${{part}})
{
if (isset(${{part}}) !== true) {
return $this;
}
{% if info.type == 'list' %}
if (is_array(${{part}}) === true) {
${{part}} = implode(",", ${{part}});
}
{% endif %}
$this->{{part}} = ${{part}};
return $this;
}
{% endif %}
{% endfor %}
{% set exception = '' %}
/**
{% for part, info in data.url.parts %}{% if info.required is not null %}{% set exception = ' * @throws \\Elasticsearch\\Common\\Exceptions\\BadMethodCallException
' %}{% endif %}{% endfor %}
{% autoescape false %}{{ exception }}{% endautoescape %}
* @return string
*/
protected function getURI()
{
{% for part, info in data.url.parts %}
{% if info.required == true %}
if (isset($this->{{ part }}) !== true) {
throw new Exceptions\RuntimeException(
'{{ part }} is required for {{ className }}'
);
}
{% endif %}
{% endfor %}
{% for part, info in data.url.parts %}
${{ part }} = $this->{{ part }};
{% endfor %}
$uri = "{{ data.url.default }}";
{% set loopCounter = 0 %}
{% for part, info in data.url.processed %}
{% if info.count > 0 %}
{% set counter = 0 %}
{% if loopCounter != 0 %}
else{% endif %}if ({% for param in info.params %}{% if counter == 0 %}isset(${{ param }}) === true{% else %} && isset(${{ param }}) === true{% endif %}{% set counter = counter + 1 %}{% endfor %})
{
$uri = "{{ info.parsedPath }}";
}
{% set loopCounter = 1 %}
{% endif %}
{% endfor %}
return $uri;
}
/**
* @return string[]
*/
protected function getParamWhitelist()
{
return array(
{% for param, options in data.url.params %}
'{{ param }}',
{% endfor %}
);
}
{% if data.body.required == true %}
/**
* @return array
* @throws \Elasticsearch\Common\Exceptions\RuntimeException
*/
protected function getBody()
{
if (isset($this->body) !== true) {
throw new Exceptions\RuntimeException('Body is required for {{ className|title }}');
}
return $this->body;
}
{% endif %}
/**
* @return string
*/
protected function getMethod()
{
{% if data.methods|length > 1 %}
//TODO Fix Me!
return '{{ data.methods|join(',') }}';
{% else %}
return '{{ data.methods[0] }}';
{% endif %}
}
}PK ?VFHw ruleset.xmlnu W+A
PK ?Vo* v v .gitmodulesnu W+A [submodule "util/elasticsearch"]
path = util/elasticsearch
url = https://github.com/elasticsearch/elasticsearch.git
PK ?VH3%,
composer.jsonnu W+A {
"name": "elasticsearch/elasticsearch",
"description": "PHP Client for Elasticsearch",
"keywords": ["search","client", "elasticsearch"],
"type": "library",
"license": "Apache-2.0",
"authors": [
{
"name": "Zachary Tong"
},
{
"name": "Enrico Zimuel"
}
],
"require": {
"php": "^7.0",
"ext-json": ">=1.3.7",
"guzzlehttp/ringphp": "~1.0",
"psr/log": "~1.0"
},
"require-dev": {
"cpliakas/git-wrapper": "^1.7 || ^2.1",
"doctrine/inflector": "^1.1",
"mockery/mockery": "^1.2",
"phpstan/phpstan-shim": "^0.9 || ^0.11",
"phpunit/phpunit": "^5.7 || ^6.5",
"squizlabs/php_codesniffer": "^3.4",
"symfony/finder": "^2.8",
"symfony/yaml": "^2.8"
},
"suggest": {
"ext-curl": "*",
"monolog/monolog": "Allows for client-level logging and tracing"
},
"autoload": {
"psr-4": {
"Elasticsearch\\": "src/Elasticsearch/"
}
},
"autoload-dev": {
"psr-4": {
"Elasticsearch\\Tests\\": "tests/Elasticsearch/Tests/",
"Elasticsearch\\IntegrationTests\\": "tests/Elasticsearch/IntegrationTests/"
}
},
"config": {
"sort-packages": true
},
"scripts": {
"phpcs": [
"phpcs --standard=ruleset.xml --extensions=php --encoding=utf-8 --tab-width=4 -sp src",
"phpcs --standard=ruleset.xml --extensions=php --encoding=utf-8 --tab-width=4 -sp tests"
],
"phpstan": [
"@php vendor/phpstan/phpstan-shim/phpstan.phar analyse -c phpstan-src.neon src --level 2 --no-progress"
]
}
}
PK ?V;03 3 CHANGELOG.mdnu W+A ## Release 6.7.0
- Removed requirement of `{type}` part in `indices.put_mapping`, see new API specification [here](https://github.com/elastic/elasticsearch/blob/v6.7.0/rest-api-spec/src/main/resources/rest-api-spec/api/indices.put_mapping.json)
- Added `seq_no_primary_term` parameter in `bulk` endpoint [#884](https://github.com/elastic/elasticsearch-php/pull/884)
- Added `include_type_name`, `if_primary_term`, `if_seq_no` in `delete` endpoint [#884](https://github.com/elastic/elasticsearch-php/pull/884)
- Added `include_type_name` in `get`, `index`, `indices.create`, `indices.field.get`, `indices.get`, `indices.mapping.get`, `indices.mapping.getfield`, `indices.mapping.put`, `indices.rollover`, `indices.template.get`, `indices.template.put` endpoints [#884](https://github.com/elastic/elasticsearch-php/pull/884)
- Added `seq_no_primary_term` in `search` endpoint [#884](https://github.com/elastic/elasticsearch-php/pull/884)
- Added `if_primary_term', 'if_seq_no`in `update` endpoint [#884](https://github.com/elastic/elasticsearch-php/pull/884)
### Testing
- Fix tests for PHP 7 with ES 6.7 [[5401479](https://github.com/elastic/elasticsearch-php/pull/884/commits/5401479)
### Docs
- [DOCS] Fix doc links in README [[5a1782d]](https://github.com/elastic/elasticsearch-php/pull/884/commits/5a1782d)
## Release 6.5.0
- Remove `_suggest` endpoint, which has disappeared from ES6 [#763](https://github.com/elastic/elasticsearch-php/pull/763)
- Fix `SearchHitIterator` key duplicates [#872](https://github.com/elastic/elasticsearch-php/pull/872)
- Fixing script get and delete by removing `lang` from endpoint url [#814](https://github.com/elastic/elasticsearch-php/pull/814)
- Fix `SearchResponseIterator` is scrolling the first page twice [#871](https://github.com/elastic/elasticsearch-php/pull/871), issue [#595](https://github.com/elastic/elasticsearch-php/issues/595)
### Docs
- [DOCS] Add reference to `parse_url()` for Extended Host Configuration [#778](https://github.com/elastic/elasticsearch-php/pull/778)
- [DOCS] Update php version requirement [#757](https://github.com/elastic/elasticsearch-php/pull/757)
- [DOCS] Update `community.asciidoc`, added `ElasticSearchQueryDSL` project [#749](https://github.com/elastic/elasticsearch-php/pull/749)
- [DOCS] Proper return type array for get method for `IndicesNamespace` [#651](https://github.com/elastic/elasticsearch-php/pull/651)
- [DOCS] Fix full docs link [#862](https://github.com/elastic/elasticsearch-php/pull/862)
- [DOCS] Update breaking-changes.asciidoc, removal of ClientBuilder::defaultLogger() [879](https://github.com/elastic/elasticsearch-php/pull/879)
### Testing
- Fix integration tests using docker [#867](https://github.com/elastic/elasticsearch-php/pull/867)
## Release 6.1.0
- Add 'wait_for_no_initializing_shards' to Cluster\Health whitelist [[98a372c]](http://github.com/elasticsearch/elasticsearch-php/commit/98a372c)
- Add 'wait_for_active_shards' to Indices\Open whitelist [[0275fe5]](http://github.com/elasticsearch/elasticsearch-php/commit/0275fe5)
- Add 'max_concurrent_searches' to msearch whitelist [[5624123]](http://github.com/elasticsearch/elasticsearch-php/commit/5624123)
- Add 'max_concurrent_shard_requests' param to MSearch endpoint [[00800c1]](http://github.com/elasticsearch/elasticsearch-php/commit/00800c1)
- Add ReloadSecureSettings endpoint [[75b32b2]](http://github.com/elasticsearch/elasticsearch-php/commit/75b32b2)
- Remove obsolete Shutdown API [[c75d690]](http://github.com/elasticsearch/elasticsearch-php/commit/c75d690)
- Fix: Restore::setBody() does not throw exceptions (#828) [[a96bb9c]](http://github.com/elasticsearch/elasticsearch-php/commit/a96bb9c)
- Fixed php 7.3 compatibility for elasticsearch 6 (#827) [[77916b2]](http://github.com/elasticsearch/elasticsearch-php/commit/77916b2)
- Fix issue with getting status of respository and snapshots. (#719) [[2d11682]](http://github.com/elasticsearch/elasticsearch-php/commit/2d11682)
- fix DeleteByQuery param white list (#748) [[8d963c6]](http://github.com/elasticsearch/elasticsearch-php/commit/8d963c6)
### Docs
- [Docs] Update elasticsearch version (#743) [[043ad4f]](http://github.com/elasticsearch/elasticsearch-php/commit/043ad4f)
- [DOCS] reuqest → request typo fix (#728) [[68db9f0]](http://github.com/elasticsearch/elasticsearch-php/commit/68db9f0)
- [DOCS] Fix documentation example of upsert (#730) [[805329b]](http://github.com/elasticsearch/elasticsearch-php/commit/805329b)
- [DOCS] Replace deprecated string type with keyword type for index operations (#736) [[a550507]](http://github.com/elasticsearch/elasticsearch-php/commit/a550507)
### Testing
- [TEST] Fix travis untarring [[0106351]](http://github.com/elasticsearch/elasticsearch-php/commit/0106351)
- [TEST] Download artifacts directly, migrate off esvm [[1e9f06c]](http://github.com/elasticsearch/elasticsearch-php/commit/1e9f06c)
- Update Travis Matrix [[aa32b12]](http://github.com/elasticsearch/elasticsearch-php/commit/aa32b12)
- [TEST] Fix teardown in yaml runner [[098030e]](http://github.com/elasticsearch/elasticsearch-php/commit/098030e)
- Add Indices/Split endpoint [[46d5a7a]](http://github.com/elasticsearch/elasticsearch-php/commit/46d5a7a)
- [TEST] Blacklist some bad yml tests [[d5edab7]](http://github.com/elasticsearch/elasticsearch-php/commit/d5edab7)
## Release 6.0.1
- Fix imports [[0106351]](http://github.com/elasticsearch/elasticsearch-php/commit/0106351)
- ClientBuilder: setLogger() and setTracer() only accept \Psr\Log\LoggerInterface (#673) [[0270c4f]](http://github.com/elasticsearch/elasticsearch-php/commit/0270c4f)
- fix for invalid GET /_aliases route. (#663) [[6d467fa]](http://github.com/elasticsearch/elasticsearch-php/commit/6d467fa)
- Remove PutTemplate endpoint, lang param of PutScript no longer used [[a13544f]](http://github.com/elasticsearch/elasticsearch-php/commit/a13544f)
Note: I'm considering PutTemplate removal a bugfix, since the API doesn't exist in ES Core anymore. Using the endpoint throws an error,
so the removal is just fixing an existing bug, hence `6.0.1` instead of `6.1.0`
### Docs
- [DOCS] Add note about separate X-Pack library to README (#694) [[6ffdef8]](http://github.com/elasticsearch/elasticsearch-php/commit/6ffdef8)
- [DOCS] add link to community index helper (#681) [[644f7f7]](http://github.com/elasticsearch/elasticsearch-php/commit/644f7f7)
- [DOCS] Add missing content for breaking changes page [[5a515ac]](http://github.com/elasticsearch/elasticsearch-php/commit/5a515ac)
- [DOCS] update autogenerated api docs [[7f2cd0b]](http://github.com/elasticsearch/elasticsearch-php/commit/7f2cd0b)
- [DOCS] Update version tables [[b824bb7]](http://github.com/elasticsearch/elasticsearch-php/commit/b824bb7)
## Release 6.0.0
- Add Ingest\ProcessorGrok endpoint [[800b1ec]](http://github.com/elasticsearch/elasticsearch-php/commit/800b1ec)
- Add Cluster\RemoteInfo endoint [[dfd8c3c]](http://github.com/elasticsearch/elasticsearch-php/commit/dfd8c3c)
- Add Unauthorized401Exception [[cc68efd]](http://github.com/elasticsearch/elasticsearch-php/commit/cc68efd)
- Add verify as acceptable query string parameter for createRepository (#665) [[885bfea]](http://github.com/elasticsearch/elasticsearch-php/commit/885bfea)
- Fix parsing of NodesInfo for Sniffing [[e22f67f]](http://github.com/elasticsearch/elasticsearch-php/commit/e22f67f)
- Do not schedule connection pool checks on 4xx level errors [[fd75e99]](http://github.com/elasticsearch/elasticsearch-php/commit/fd75e99)
- Add 'terminate_after' to Count endpoint whitelist (#634) [[c3cacd7]](http://github.com/elasticsearch/elasticsearch-php/commit/c3cacd7)
### Docs
- [DOCS] Flip Branch / PHP Version table (#656) [[fa7bfb3]](http://github.com/elasticsearch/elasticsearch-php/commit/fa7bfb3)
### Testing
- [TEST] use proper TestCase parent clsas [[766b440]](http://github.com/elasticsearch/elasticsearch-php/commit/766b440)
- [TEST] add PHPStan to build (#628) [[946cd65]](http://github.com/elasticsearch/elasticsearch-php/commit/946cd65)
- [TEST] Fix some PHPCS violations in tests [[18a38dd]](http://github.com/elasticsearch/elasticsearch-php/commit/18a38dd)
- [src] add PHP_CodeSniffer (#647) [[24900ef]](http://github.com/elasticsearch/elasticsearch-php/commit/24900ef)
- [TEST] add PHP_CodeSniffer to build (#638) [[088a509]](http://github.com/elasticsearch/elasticsearch-php/commit/088a509)
- [TEST] Use tests from corresponding ES version (#649) [[75c6680]](http://github.com/elasticsearch/elasticsearch-php/commit/75c6680)
- [TEST] Add support for `bad_request` in yaml runner [[ad86f91]](http://github.com/elasticsearch/elasticsearch-php/commit/ad86f91)
- [TEST] `max_compilations_per_minute` is now `max_compilations_rate` [[ebdba06]](http://github.com/elasticsearch/elasticsearch-php/commit/ebdba06)
- [TEST] print elasticsearch.log if cluster fails to start [[fe796aa]](http://github.com/elasticsearch/elasticsearch-php/commit/fe796aa)
- [TEST] move integration test to dedicated test file [[71ccfc1]](http://github.com/elasticsearch/elasticsearch-php/commit/71ccfc1)
- [TEST] Client does not support accepting Yaml format responses [[fc9a9f9]](http://github.com/elasticsearch/elasticsearch-php/commit/fc9a9f9)
## Release 6.0.0-beta1
Woo!
- Use upper-case "Host" header [[045aac4]](http://github.com/elasticsearch/elasticsearch-php/commit/045aac4)
- Add 'allow_no_indices' param to Indices\Delete whitelist [[3a3a5ab]](http://github.com/elasticsearch/elasticsearch-php/commit/3a3a5ab)
- Add 'verbose' param to Snapshot\Get whitelist [[b70b933]](http://github.com/elasticsearch/elasticsearch-php/commit/b70b933)
- Add 'pre_filter_shard_size' param to Search whitelist [[f708d9d]](http://github.com/elasticsearch/elasticsearch-php/commit/f708d9d)
- Add 'ignore_unavailable' param to Indices\Delete whitelist [[8133021]](http://github.com/elasticsearch/elasticsearch-php/commit/8133021)
- Add 'include_defaults' param to Cluster\Settings\Get whitelist [[8e5ab38]](http://github.com/elasticsearch/elasticsearch-php/commit/8e5ab38)
### Docs
- [DOCS] Remove Sami from composer.json and update docs (#619) [[fcd5ff1]](http://github.com/elasticsearch/elasticsearch-php/commit/fcd5ff1)
- [Docs] recommend composer/ca-bundle instead of Kdyby/CurlCaBundle (#613) [[7f43b2e]](http://github.com/elasticsearch/elasticsearch-php/commit/7f43b2e)
### Testing
- [TEST] Fix content-type assertions in test to match case [[5b37117]](http://github.com/elasticsearch/elasticsearch-php/commit/5b37117)
- Capitalize 'Content-Type' for maximum compatibility [[b8ad96c]](http://github.com/elasticsearch/elasticsearch-php/commit/b8ad96c)
- [TEST] Use percentage watermarks to be compatible with default flood [[95d2f89]](http://github.com/elasticsearch/elasticsearch-php/commit/95d2f89)
- [TEST] remove watermark flood from static config [[9b71940]](http://github.com/elasticsearch/elasticsearch-php/commit/9b71940)
- Shrink API was not setting body correctly [[e0f0985]](http://github.com/elasticsearch/elasticsearch-php/commit/e0f0985)
- [TEST] Add some missing and required static configs [[38febbe]](http://github.com/elasticsearch/elasticsearch-php/commit/38febbe)
- [TEST] Allow skipping individual tests inside of test file [[51b9b9b]](http://github.com/elasticsearch/elasticsearch-php/commit/51b9b9b)
- Travis: add PHP 7.2 + ES 6.0 to build matrix (#622) [[061f100]](http://github.com/elasticsearch/elasticsearch-php/commit/061f100)
- [TEST] tests code cleanup (#618) [[dc5d18c]](http://github.com/elasticsearch/elasticsearch-php/commit/dc5d18c)
- [TEST] Fix RoundRobinSelector Tests (#617) [[23a0ba8]](http://github.com/elasticsearch/elasticsearch-php/commit/23a0ba8)
- [TEST] skip new percentile tests for now [[b5d9613]](http://github.com/elasticsearch/elasticsearch-php/commit/b5d9613)
- [TEST] drop HHVM from build [#611] (#616) [[21a2d24]](http://github.com/elasticsearch/elasticsearch-php/commit/21a2d24)
- [TEST] Skip cat.aliases/20_headers.yml [[c83ca74]](http://github.com/elasticsearch/elasticsearch-php/commit/c83ca74)
- [TEST] YamlRunnerTest should run both .yml and .yaml files [[98c2646]](http://github.com/elasticsearch/elasticsearch-php/commit/98c2646)
- [TEST] build against ES 6 on Travis [[b5886a8]](http://github.com/elasticsearch/elasticsearch-php/commit/b5886a8)
- [TEST] drop HHVM from build [#611] [[0a7b402]](http://github.com/elasticsearch/elasticsearch-php/commit/0a7b402)
- [TEST] test tweaks to appease stricter types [[51f189e]](http://github.com/elasticsearch/elasticsearch-php/commit/51f189e)
- Fix ClientBuilder - pass correct argument for Elasticsearch\Endpoints\MsearchTemplate::__construct. (#605) [[5f83b52]](http://github.com/elasticsearch/elasticsearch-php/commit/5f83b52)
- [TEST] improve code quality of tests (#610) [[9ea2156]](http://github.com/elasticsearch/elasticsearch-php/commit/9ea2156)
- [TEST] Support headers in yaml runner, do some bad-comment cleaning [[57b5489]](http://github.com/elasticsearch/elasticsearch-php/commit/57b5489)
- [TEST] fix handling of format for Cat tests [[a24b7d1]](http://github.com/elasticsearch/elasticsearch-php/commit/a24b7d1)
- [TEST] test files are now .yml instead of .yaml [[ceac5bd]](http://github.com/elasticsearch/elasticsearch-php/commit/ceac5bd)
PK ?VeQ} } tests/bootstrap.phpnu W+A expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('$logger must implement \Psr\Log\LoggerInterface!');
ClientBuilder::create()->setLogger(new \Elasticsearch\Tests\ClientBuilder\DummyLogger());
}
public function testClientBuilderThrowsExceptionForIncorrectTracerClass()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('$tracer must implement \Psr\Log\LoggerInterface!');
ClientBuilder::create()->setTracer(new \Elasticsearch\Tests\ClientBuilder\DummyLogger());
}
}
PK ?VNt 4 tests/Elasticsearch/Tests/ClientIntegrationTests.phpnu W+A
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elasticsearch.org
*/
class ClientIntegrationTests extends \PHPUnit\Framework\TestCase
{
public function testCustomQueryParams()
{
$client = Elasticsearch\ClientBuilder::create()
->setHosts([getenv('ES_TEST_HOST')])
->build();
$getParams = [
'index' => 'test',
'type' => 'test',
'id' => 1,
'parent' => 'abc',
'custom' => ['customToken' => 'abc', 'otherToken' => 123],
'client' => ['ignore' => 400]
];
$exists = $client->exists($getParams);
$this->assertFalse((bool) $exists);
}
}
PK ?VW>lg g 7 tests/Elasticsearch/Tests/ClientBuilder/DummyLogger.phpnu W+A
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elasticsearch.org
*/
class YamlRunnerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Symfony\Component\Yaml\Yaml Yaml parser for reading integrations tests
*/
private $yaml;
/**
* @var \Elasticsearch\Client client used by elasticsearch
*/
private $client;
/**
* @var string Es version
*/
private static $esVersion;
/**
* @var string[] A list of supported features
*/
private static $supportedFeatures = [
'stash_in_path', 'warnings', 'headers'
];
/**
* @var array A mapping for endpoint when there is a reserved keywords for the method / namespace name
*/
private static $endpointMapping = [
'tasks' => [
'list' => ['tasksList', 'tasks'],
],
];
private static $skippedTests = [
'nodes.stats/30_discovery.yml#Discovery stats' => 'Failing on ES 6.1+: nodes.$master.discovery is an empty array, expected to have cluster_state_queue field in it',
'indices.stats/20_translog.yml#Translog retention' => 'Failing on ES 6.3+: Failed asserting that 495 is equal to or is less than \'$creation_size\'',
'indices.shrink/30_copy_settings.yml#Copy settings during shrink index' => 'Failing on ES 6.4+: Failed to match in test "Copy settings during shrink index". Expected [\'4\'] does not match [false] ',
];
private static $skippedTestsIfPhpLessThan = [
// Failing on ES 6.7+ only with PHP 7.0: Cannot access empty property
'indices.put_mapping/11_basic_with_types.yml#Create index with invalid mappings' => '7.1.0',
'indices.put_mapping/10_basic.yml#Create index with invalid mappings' => '7.1.0',
'indices.create/11_basic_with_types.yml#Create index with invalid mappings' => '7.1.0',
'indices.create/11_basic_with_types.yml#Create index with no type mappings' => '7.1.0',
'indices.create/10_basic.yml#Create index with invalid mappings' => '7.1.0',
];
/**
* @var array A list of skipped test with their reasons
*/
private static $skippedFiles = [
'cat.nodeattrs/10_basic.yml' => 'Using java regex fails in PHP',
'cat.nodeattrs/10_basic.yaml' => 'Using java regex fails in PHP',
'cat.repositories/10_basic.yml' => 'Using java regex fails in PHP',
'cat.repositories/10_basic.yaml' => 'Using java regex fails in PHP',
'indices.shrink/10_basic.yml' => 'Shrink tests seem to require multiple nodes',
'indices.shrink/10_basic.yaml' => 'Shrink tests seem to require multiple nodes',
'indices.rollover/10_basic.yml' => 'Rollover test seems buggy atm',
'indices.rollover/10_basic.yaml' => 'Rollover test seems buggy atm',
];
/**
* @var array A list of files to skip completely, due to fatal parsing errors
*/
private static $fatalFiles = [
'indices.create/10_basic.yml' => 'Temporary: Yaml parser doesnt support "inline" empty keys',
'indices.create/10_basic.yaml' => 'Temporary: Yaml parser doesnt support "inline" empty keys',
'indices.put_mapping/10_basic.yml' => 'Temporary: Yaml parser doesnt support "inline" empty keys',
'indices.put_mapping/10_basic.yaml' => 'Temporary: Yaml parser doesnt support "inline" empty keys',
'search/110_field_collapsing.yml' => 'Temporary: parse error, malformed inline yaml',
'search/110_field_collapsing.yaml' => 'Temporary: parse error, malformed inline yaml',
'range/10_basic.yml' => 'Temporary: parse error, malformed inline yaml',
'cat.nodes/10_basic.yml' => 'Temporary: parse error, something about $body: |',
'cat.nodes/10_basic.yaml' => 'Temporary: parse error, something about $body: |',
'search.aggregation/180_percentiles_tdigest_metric.yml' => 'array of objects, unclear how to fix',
'search.aggregation/190_percentiles_hdr_metric.yml' => 'array of objects, unclear how to fix',
'search/190_index_prefix_search.yml' => 'bad yaml array syntax',
'search.aggregation/230_composite.yml' => 'bad yaml array syntax',
'search/30_limits.yml' => 'bad regex'
];
/**
* Return the elasticsearch host
*
* @return string
*/
public static function getHost(): string
{
if (getenv('ES_TEST_HOST') !== false) {
return getenv('ES_TEST_HOST');
}
echo 'Environment variable for elasticsearch test cluster (ES_TEST_HOST) not defined. Exiting yaml test';
exit;
}
public static function setUpBeforeClass()
{
$host = static::getHost();
echo "Test Host: $host\n";
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
static::$esVersion = $response['version']['number'];
echo "ES Version: ".static::$esVersion."\n";
}
public function setUp()
{
$this->clean();
$this->client = Elasticsearch\ClientBuilder::create()->setHosts([self::getHost()])->build();
}
/**
* @dataProvider yamlProvider
* @group sync
*/
public function testIntegration($testProcedure, bool $skip, $setupProcedure, $teardownProcedure, string $fileName)
{
if ($skip) {
static::markTestIncomplete($testProcedure);
}
if (array_key_exists($fileName, static::$skippedFiles)) {
static::markTestSkipped(static::$skippedFiles[$fileName]);
}
if (null !== $setupProcedure) {
$this->processProcedure(current($setupProcedure), 'setup', $fileName);
$this->waitForYellow();
}
try {
$this->processProcedure(current($testProcedure), key($testProcedure), $fileName);
} finally {
if (null !== $teardownProcedure) {
$this->processProcedure(current($teardownProcedure), 'teardown', $fileName);
$this->waitForYellow();
}
}
}
/**
* @dataProvider yamlProvider
* @group async
*/
public function testAsyncIntegration($testProcedure, bool $skip, $setupProcedure, $teardownProcedure, string $fileName)
{
if ($skip) {
static::markTestIncomplete($testProcedure);
}
if (array_key_exists($fileName, static::$skippedFiles)) {
static::markTestSkipped(static::$skippedFiles[$fileName]);
}
if (null !== $setupProcedure) {
$this->processProcedure(current($setupProcedure), 'setup', $fileName);
$this->waitForYellow();
}
try {
$this->processProcedure(current($testProcedure), key($testProcedure), $fileName, true);
} finally {
if (null !== $teardownProcedure) {
$this->processProcedure(current($teardownProcedure), 'teardown', $fileName);
$this->waitForYellow();
}
}
}
/**
* Process a procedure
*
* @param array $procedure
* @param string $name
* @param string $fileName
* @param bool $async
*/
public function processProcedure(array $procedure, string $name, string $fileName, bool $async = false)
{
$lastOperationResult = null;
$context = [];
if (array_key_exists("$fileName#$name", static::$skippedTests)) {
static::markTestSkipped(static::$skippedTests["$fileName#$name"]);
}
foreach ($procedure as $operation) {
$lastOperationResult = $this->processOperation($operation, $lastOperationResult, $context, $name, $async);
}
}
/**
* Process an operation
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param array $context
* @param string $testName
* @param bool $async
*
* @return mixed
*/
public function processOperation($operation, $lastOperationResult, array &$context, string $testName, bool $async = false)
{
$operationName = array_keys((array)$operation)[0];
if ('do' === $operationName) {
return $this->operationDo($operation->{$operationName}, $lastOperationResult, $context, $testName, $async);
}
if ('is_false' === $operationName) {
return $this->operationIsFalse($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('is_true' === $operationName) {
return $this->operationIsTrue($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('match' === $operationName) {
return $this->operationMatch($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('gte' === $operationName) {
return $this->operationGreaterThanOrEqual($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('gt' === $operationName) {
return $this->operationGreaterThan($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('lte' === $operationName) {
return $this->operationLessThanOrEqual($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('t' === $operationName) {
return $this->operationLessThan($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('length' === $operationName) {
return $this->operationLength($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('set' === $operationName) {
return $this->operationSet($operation->{$operationName}, $lastOperationResult, $context, $testName);
}
if ('skip' === $operationName) {
return $this->operationSkip($operation->{$operationName}, $lastOperationResult, $testName);
}
self::markTestIncomplete(sprintf('Operation %s not supported for test "%s"', $operationName, $testName));
}
/**
* Do something on the client
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param array $context
* @param string $testName
* @param bool $async
*
* @throws \Exception
*
* @return mixed
*/
public function operationDo($operation, $lastOperationResult, &$context, string $testName, bool $async = false)
{
$expectedError = null;
$expectedWarnings = null;
$headers = null;
// Check if a error must be caught
if ('catch' === key($operation)) {
$expectedError = current($operation);
next($operation);
}
// Check if a warning must be caught
if ('warnings' === key($operation)) {
$expectedWarnings = current($operation);
next($operation);
}
// Any specific headers to add?
if ('headers' === key($operation)) {
$headers = current($operation);
next($operation);
}
$endpointInfo = explode('.', key($operation));
/**
* @var \stdClass $endpointParams
*/
$endpointParams = $this->replaceWithContext(current($operation), $context);
$caller = $this->client;
$namespace = null;
$method = null;
if (count($endpointInfo) === 1) {
$method = Inflector::camelize($endpointInfo[0]);
}
if (count($endpointInfo) === 2) {
$namespace = $endpointInfo[0];
$method = Inflector::camelize($endpointInfo[1]);
}
if (is_object($endpointParams) === true && property_exists($endpointParams, 'ignore')) {
$ignore = $endpointParams->ignore;
unset($endpointParams->ignore);
$endpointParams->client['ignore'] = $ignore;
}
if ($async) {
$endpointParams->client['future'] = true;
}
if ($headers != null) {
$endpointParams->client['headers'] = $headers;
}
if (!is_string($method)) {
throw new \Exception('$method must be string');
}
list($method, $namespace) = $this->mapEndpoint($method, $namespace);
if (null !== $namespace) {
$caller = $caller->$namespace();
}
if (null === $method) {
self::markTestIncomplete(sprintf('Invalid do operation for test "%s"', $testName));
}
if (!method_exists($caller, $method)) {
self::markTestIncomplete(sprintf('Method "%s" not implement in "%s"', $method, get_class($caller)));
}
// TODO remove this after cat testing situation resolved
if ($caller instanceof Elasticsearch\Namespaces\CatNamespace) {
if (!isset($endpointParams->format)) {
$endpointParams->format = 'text';
}
}
// Exist* methods have to be manually 'unwrapped' into true/false for async
if (strpos($method, "exist") !== false && $async === true) {
return $this->executeAsyncExistRequest($caller, $method, $endpointParams, $expectedError, $expectedWarnings, $testName);
}
return $this->executeRequest($caller, $method, $endpointParams, $expectedError, $expectedWarnings, $testName);
}
/**
* Obtain the response from the server
*
* @param object $caller
* @param string $method
* @param object $endpointParams
* @param string|null $expectedError
* @param null $expectedWarnings
* @param string $testName
*
* @throws \Exception
*
* @return array|mixed
*/
public function executeRequest($caller, string $method, $endpointParams, $expectedError, $expectedWarnings, string $testName)
{
try {
$response = $caller->$method($endpointParams);
while ($response instanceof FutureArrayInterface) {
$response = $response->wait();
}
$this->checkForWarnings($expectedWarnings);
return $response;
} catch (\Exception $exception) {
if (null !== $expectedError) {
return $this->assertException($exception, $expectedError, $testName);
}
$msg = $exception->getMessage()
."\nException in ".get_class($caller)." with [$method].\n Context:\n"
.var_export($endpointParams, true);
throw new \Exception($msg, 0, $exception);
}
}
/**
* Obtain the response when it is an Exists* method. These are converted into
* true/false responses
*
* @param object $caller
* @param string $method
* @param object $endpointParams
* @param string|null $expectedError
* @param null $expectedWarnings
* @param string $testName
*
* @throws \Exception
*
* @return bool|mixed[]|null
*/
public function executeAsyncExistRequest($caller, $method, $endpointParams, $expectedError, $expectedWarnings, $testName)
{
try {
$response = $caller->$method($endpointParams);
while ($response instanceof FutureArrayInterface) {
$response = $response->wait();
}
$this->checkForWarnings($expectedWarnings);
if ($response['status'] === 200) {
return true;
} else {
return false;
}
} catch (Missing404Exception $exception) {
return false;
} catch (RoutingMissingException $exception) {
return false;
} catch (\Exception $exception) {
if (null !== $expectedError) {
return $this->assertException($exception, $expectedError, $testName);
}
throw $exception;
}
}
public function checkForWarnings($expectedWarnings)
{
$last = $this->client->transport->getLastConnection()->getLastRequestInfo();
// We have some warnings to check
if ($expectedWarnings !== null) {
if (isset($last['response']['headers']['Warning']) === true) {
foreach ($last['response']['headers']['Warning'] as $warning) {
//$position = array_search($warning, $expectedWarnings);
$position = false;
foreach ($expectedWarnings as $index => $value) {
if (stristr($warning, $value) !== false) {
$position = $index;
break;
}
}
if ($position !== false) {
// found the warning
unset($expectedWarnings[$position]);
} else {
// didn't find, throw error
//throw new \Exception("Expected to find warning [$warning] but did not.");
}
}
if (count($expectedWarnings) > 0) {
print_r($last['response']);
throw new \Exception("Expected to find more warnings: ". print_r($expectedWarnings, true));
}
}
}
// Check to make sure we're adding headers
$this->assertArrayHasKey('Content-Type', $last['request']['headers'], print_r($last['request']['headers'], true));
$this->assertSame('application/json', $last['request']['headers']['Content-Type'][0], print_r($last['request']['headers'], true));
$this->assertArrayHasKey('Accept', $last['request']['headers'], print_r($last['request']['headers'], true));
$this->assertSame('application/json', $last['request']['headers']['Accept'][0], print_r($last['request']['headers'], true));
}
/**
* Check if a field in the last operation is false
*
* @param string $operation
* @param array|string|null $lastOperationResult
* @param array $context
* @param string $testName
*/
public function operationIsFalse(string $operation, $lastOperationResult, &$context, string $testName)
{
$value = (bool)$this->resolveValue($lastOperationResult, $operation, $context);
$msg = "Failed to assert that a value is false in test \"$testName\"\n"
."$operation was [".print_r($value, true)."]"
.var_export($lastOperationResult, true);
$this->assertFalse($value, $msg);
return $lastOperationResult;
}
/**
* Check if a field in the last operation is true
*
* @param string $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationIsTrue(string $operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, $operation, $context);
$msg = "Failed to assert that a value is true in test \"$testName\"\n"
."$operation was [".print_r($value, true)."]"
.var_export($lastOperationResult, true);
$this->assertNotEquals(0, $value, $msg);
$this->assertNotFalse($value, $msg);
$this->assertNotNull($value, $msg);
$this->assertNotEquals('', $msg);
return $lastOperationResult;
}
/**
* Check if a field in the last operation match an expected value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationMatch($operation, $lastOperationResult, &$context, string $testName)
{
$key = key($operation);
if ($key === '$body') {
$match = $lastOperationResult;
} else {
$match = $this->resolveValue($lastOperationResult, $key, $context);
}
$expected = $this->replaceWithContext(current($operation), $context);
$msg = "Failed to match in test \"$testName\". Expected ["
.var_export($expected, true)."] does not match [".var_export($match, true)."]\n".var_export($lastOperationResult, true);
if ($expected instanceof \stdClass) {
// Avoid stdClass / array mismatch
$expected = json_decode(json_encode($expected), true);
$match = json_decode(json_encode($match), true);
$this->assertEquals($expected, $match, $msg);
} elseif (is_string($expected) && preg_match('#^/.+?/$#s', $expected)) {
$this->assertRegExp($this->formatRegex($expected), $match, $msg);
} else {
$this->assertEquals($expected, $match, $msg);
}
return $lastOperationResult;
}
/**
* Check if a field in the last operation is greater than or equal a value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationGreaterThanOrEqual($operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, key($operation), $context);
$expected = current($operation);
$this->assertGreaterThanOrEqual($expected, $value, 'Failed to gte in test ' . $testName);
return $lastOperationResult;
}
/**
* Check if a field in the last operation is greater than a value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationGreaterThan($operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, key($operation), $context);
$expected = current($operation);
$this->assertGreaterThan($expected, $value, 'Failed to gt in test ' . $testName);
return $lastOperationResult;
}
/**
* Check if a field in the last operation is less than or equal a value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationLessThanOrEqual($operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, key($operation), $context);
$expected = current($operation);
$this->assertLessThanOrEqual($expected, $value, 'Failed to lte in test ' . $testName);
return $lastOperationResult;
}
/**
* Check if a field in the last operation is less than a value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationLessThan($operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, key($operation), $context);
$expected = current($operation);
$this->assertLessThan($expected, $value, 'Failed to lt in test ' . $testName);
return $lastOperationResult;
}
/**
* Check if a field in the last operation has length of a value
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationLength($operation, $lastOperationResult, &$context, string $testName)
{
$value = $this->resolveValue($lastOperationResult, key($operation), $context);
$expected = current($operation);
$this->assertCount($expected, $value, 'Failed to gte in test ' . $testName);
return $lastOperationResult;
}
/**
* Set a variable into context from last operation
*
* @param object $operation
* @param array|string|null $lastOperationResult
* @param array $context
* @param string $testName
*/
public function operationSet($operation, $lastOperationResult, &$context, string $testName)
{
$key = key($operation);
$value = $this->resolveValue($lastOperationResult, $key, $context);
$variable = current($operation);
$context['$' . $variable] = $value;
return $lastOperationResult;
}
/**
* Skip an operation depending on Elasticsearch Version
*
* @param \stdClass &object $operation
* @param array|string|null $lastOperationResult
* @param string $testName
*/
public function operationSkip($operation, $lastOperationResult, string $testName)
{
if (is_object($operation) !== true) {
return $lastOperationResult;
}
if (property_exists($operation, 'features')) {
if (is_array($operation->features)) {
if (count(array_intersect($operation->features, static::$supportedFeatures)) != count($operation->features)) {
static::markTestSkipped(sprintf('Feature(s) %s not supported in test "%s"', json_encode($operation->features), $testName));
}
} else {
if (!in_array($operation->features, static::$supportedFeatures, true)) {
static::markTestSkipped(sprintf('Feature(s) %s not supported in test "%s"', json_encode($operation->features), $testName));
}
}
}
if (property_exists($operation, 'version')) {
$version = $operation->version;
$version = str_replace(" ", "", $version);
$version = explode("-", $version);
if (isset($version[0]) && $version[0] == 'all') {
static::markTestSkipped(sprintf('Skip test "%s", as all versions should be skipped (%s)', $testName, $operation->reason));
}
if (!isset($version[0]) || $version[0] === "") {
$version[0] = ~PHP_INT_MAX;
}
if (!isset($version[1]) || $version[1] === "") {
$version[1] = PHP_INT_MAX;
}
if (version_compare(static::$esVersion, (string)$version[0], '>=') && version_compare(static::$esVersion, (string)$version[1], '<=')) {
static::markTestSkipped(sprintf('Skip test "%s", as version %s should be skipped (%s)', $testName, static::$esVersion, $operation->reason));
}
}
return $lastOperationResult;
}
/**
* Assert an expected error
*
* @param \Exception $exception
* @param string $expectedError
* @param string $testName
*
* @return array|null
*/
private function assertException(\Exception $exception, string $expectedError, string $testName)
{
if (is_string($expectedError) && preg_match('#^/.+?/$#', $expectedError)) {
$this->assertRegExp($expectedError, $exception->getMessage(), 'Failed to catch error in test ' . $testName);
} elseif ($exception instanceof BadRequest400Exception && $expectedError === 'bad_request') {
$this->assertTrue(true);
} elseif ($exception instanceof Unauthorized401Exception && $expectedError === 'unauthorized') {
$this->assertTrue(true);
} elseif ($exception instanceof Missing404Exception && $expectedError === 'missing') {
$this->assertTrue(true);
} elseif ($exception instanceof Conflict409Exception && $expectedError === 'conflict') {
$this->assertTrue(true);
} elseif ($exception instanceof Forbidden403Exception && $expectedError === 'forbidden') {
$this->assertTrue(true);
} elseif ($exception instanceof RequestTimeout408Exception && $expectedError === 'request_timeout') {
$this->assertTrue(true);
} elseif ($exception instanceof BadRequest400Exception && $expectedError === 'request') {
$this->assertTrue(true);
} elseif ($exception instanceof ServerErrorResponseException && $expectedError === 'request') {
$this->assertTrue(true);
} elseif ($exception instanceof \RuntimeException && $expectedError === 'param') {
$this->assertTrue(true);
} else {
$this->assertContains($expectedError, $exception->getMessage());
}
if ($exception->getPrevious() !== null) {
return json_decode($exception->getPrevious()->getMessage(), true);
}
return json_decode($exception->getMessage(), true);
}
/**
* Provider list of document to test
*
* @return array
*/
public function yamlProvider(): array
{
$this->yaml = new Yaml();
$path = __DIR__ . '/../../../util/elasticsearch/rest-api-spec/src/main/resources/rest-api-spec/test';
$files = [];
$finder = new Finder();
$finder->in($path);
$finder->files();
$finder->name('*.yml');
// *.yaml files should be included until the library is ES 6.0+ only
$finder->name('*.yaml');
$filter = getenv('TEST_CASE') !== false ? getenv('TEST_CASE') : null;
/**
* @var SplFileInfo $file
*/
foreach ($finder as $file) {
$files = array_merge($files, $this->splitDocument($file, $path, $filter));
}
return $files;
}
/**
* Return the real namespace / method couple for elasticsearch php
*
* @param string $method
* @param string|null $namespace
*
* @return array
*/
private function mapEndpoint(string $method, $namespace = null): array
{
if (null === $namespace && array_key_exists($method, static::$endpointMapping)) {
return static::$endpointMapping[$method];
}
if (null !== $namespace && array_key_exists($namespace, static::$endpointMapping) && array_key_exists($method, static::$endpointMapping[$namespace])) {
return static::$endpointMapping[$namespace][$method];
}
return [$method, $namespace];
}
/**
* Replace contextual variable into a bunch of data
*
* @param object|array|string|integer $data
* @param array $context
*
* @return mixed
*/
private function replaceWithContext($data, array $context)
{
if (empty($context)) {
return $data;
}
if (is_string($data)) {
if (array_key_exists($data, $context)) {
return $context[$data];
}
}
if (!is_array($data) && !$data instanceof \stdClass) {
return $data;
}
foreach ($data as $key => &$value) {
$value = $this->replaceWithContext($value, $context);
}
return $data;
}
/**
* Resolve a value into an array given a specific field
*
* @param mixed $result
* @param string $field
* @param array $context
* @return mixed
*/
private function resolveValue($result, $field, array &$context)
{
if (empty($field)) {
return $result;
}
foreach ($context as $key => $value) {
$field = preg_replace('/('.preg_quote($key, '/').')/', $value, $field);
}
$operationSplit = explode('.', $field);
$value = $result;
do {
$key = array_shift($operationSplit);
if (substr($key, -1) === '\\') {
$key = substr($key, 0, -1) . '.' . array_shift($operationSplit);
}
if (!is_array($value)) {
return $value;
}
if (!array_key_exists($key, $value)) {
return false;
}
$value = $value[$key];
} while (count($operationSplit) > 0);
return $value;
}
/**
* Format a regex for PHP
*
* @param string $regex
*
* @return string
*/
private function formatRegex(string $regex): string
{
$regex = trim($regex);
$regex = substr($regex, 1, -1);
$regex = str_replace('/', '\\/', $regex);
$regex = '/' . $regex . '/mx';
return $regex;
}
/**
* Split file content into multiple document
*
* @param SplFileInfo $file
* @param string $path;
*
* @return array
*/
private function splitDocument(SplFileInfo $file, string $path, string $filter = null): array
{
$fileContent = $file->getContents();
// cleanup some bad comments
$fileContent = str_replace('"#', '" #', $fileContent);
$documents = explode("---\n", $fileContent);
$documents = array_filter(
$documents,
function ($item) {
return trim($item) !== '';
}
);
$documentsParsed = [];
$setup = null;
$setupSkip = false;
$teardown = null;
$fileName = str_replace($path . '/', '', $file);
if (array_key_exists($fileName, static::$fatalFiles)) {
echo "Skipping: $fileName. ".static::$fatalFiles[$fileName]."\n";
return [];
}
if (null !== $filter && !preg_match('/'.preg_quote($filter, '/').'/', $fileName)) {
return [];
}
$skip = false;
$documentParsed = null;
foreach ($documents as $documentString) {
// Extract test name
if (preg_match('/"([^"]+)"/', $documentString, $matches)) {
$testName = $matches[1];
// Skip YAML parsing if test is signed to be skipped and if PHP is < version specified
// To prevent YAML parse error, e.g. empty property
if (array_key_exists("$fileName#$testName", static::$skippedTestsIfPhpLessThan)) {
if (version_compare(PHP_VERSION, static::$skippedTestsIfPhpLessThan["$fileName#$testName"], '<')) {
continue;
}
}
}
// TODO few bad instances of teardown, should be fixed in upstream but this is a quick fix locally
$documentString = str_replace(" teardown:", "teardown:", $documentString);
try {
if (!$setupSkip) {
$documentParsed = $this->yaml->parse($documentString, false, false, true);
$skip = false;
}
} catch (ParseException $exception) {
$documentParsed = sprintf(
"[ParseException]Cannot run this test as it cannot be parsed (%s) in file %s",
$exception->getMessage(),
$fileName
);
if (preg_match("#\nsetup:#mx", $documentString)) {
$setupSkip = true;
}
$skip = true;
} catch (\Exception $exception) {
$documentParsed = sprintf(
"[Exception] Cannot run this test as it generated an exception (%s) in file %s",
$exception->getMessage(),
$fileName
);
if (preg_match("#\nsetup:#mx", $documentString)) {
$setupSkip = true;
}
$skip = true;
}
if (!$skip && key($documentParsed) === 'setup') {
$setup = $documentParsed;
$setupSkip = $skip;
} elseif (!$teardown && key($documentParsed) === 'teardown') {
$teardown = $documentParsed;
} else {
$documentsParsed[] = [$documentParsed, $skip || $setupSkip, $setup, $teardown, $fileName];
}
}
return $documentsParsed;
}
/**
* Clean the cluster
*/
private function clean()
{
$host = static::getHost();
$ch = curl_init($host."/*");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
$ch = curl_init($host."/_template/*");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
$ch = curl_init($host."/_analyzer/*");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
$ch = curl_init($host."/_snapshot/_all");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
if ($response != "{}") {
$response = json_decode($response, true);
foreach ($response as $repo => $settings) {
if ($settings['type'] == 'fs') {
$ch = curl_init($host."/_snapshot/$repo/_all?ignore_unavailable");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$snapshots = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach ($snapshots['snapshots'] as $snapshot) {
$snapshotName = $snapshot['snapshot'];
$ch = curl_init($host."/_snapshot/$repo/$snapshotName");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
}
$ch = curl_init($host."/_snapshot/$repo");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
curl_close($ch);
}
}
}
$this->rmDirRecursively('/tmp/test_repo_create_1_loc');
$this->rmDirRecursively('/tmp/test_repo_restore_1_loc');
$this->rmDirRecursively('/tmp/test_cat_repo_1_loc');
$this->rmDirRecursively('/tmp/test_cat_repo_2_loc');
$this->rmDirRecursively('/tmp/test_cat_snapshots_1_loc');
$this->waitForYellow();
}
private function rmDirRecursively(string $dir)
{
if (!is_dir($dir)) {
return;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
$todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
$todo($fileinfo->getRealPath());
}
rmdir($dir);
}
/**
* Wait for cluster to be in a "YELLOW" state
*/
private function waitForYellow()
{
$host = static::getHost();
$ch = curl_init("$host/_cluster/health?wait_for_status=yellow&timeout=50s");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = json_decode(curl_exec($ch), true);
$counter = 0;
while ($response['status'] === 'red') {
sleep(0.5);
$response = json_decode(curl_exec($ch), true);
++$counter;
if ($counter > 10) {
echo "Aborting test due to failure in clearing cluster.\n";
echo print_r($response, true);
exit;
}
}
curl_close($ch);
}
}
PK ?Vh H tests/Elasticsearch/Tests/Serializers/EverythingToJSONSerializerTest.phpnu W+A 'field'];
$ret = $serializer->serialize($body);
$body = json_encode($body, JSON_PRESERVE_ZERO_FRACTION);
$this->assertSame($body, $ret);
}
public function testSerializeString()
{
$serializer = new EverythingToJSONSerializer();
$body = 'abc';
$ret = $serializer->serialize($body);
$body = '"abc"';
$this->assertSame($body, $ret);
}
public function testDeserializeJSON()
{
$serializer = new EverythingToJSONSerializer();
$body = '{"field":"value"}';
$ret = $serializer->deserialize($body, []);
$body = json_decode($body, true);
$this->assertSame($body, $ret);
}
}
PK ?VƐ C tests/Elasticsearch/Tests/Serializers/ArrayToJSONSerializerTest.phpnu W+A 'field'];
$ret = $serializer->serialize($body);
$body = json_encode($body, JSON_PRESERVE_ZERO_FRACTION);
$this->assertSame($body, $ret);
}
public function testSerializeString()
{
$serializer = new ArrayToJSONSerializer();
$body = 'abc';
$ret = $serializer->serialize($body);
$this->assertSame($body, $ret);
}
public function testDeserializeJSON()
{
$serializer = new ArrayToJSONSerializer();
$body = '{"field":"value"}';
$ret = $serializer->deserialize($body, []);
$body = json_decode($body, true);
$this->assertSame($body, $ret);
}
}
PK ?Vk9s s D tests/Elasticsearch/Tests/Helper/Iterators/SearchHitIteratorTest.phpnu W+A
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://Elasticsearch.org
*/
class SearchHitIteratorTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
$this->searchResponse = Mockery::mock(SearchResponseIterator::class);
}
public function tearDown()
{
Mockery::close();
}
public function testWithNoResults()
{
$this->searchResponse->shouldReceive('rewind')
->once()
->ordered();
$this->searchResponse->shouldReceive('current')
->once()
->ordered()
->andReturn([]);
$this->searchResponse->shouldReceive('valid')
->twice()
->ordered()
->andReturn(false);
$searchHit = new SearchHitIterator($this->searchResponse);
$this->assertCount(0, $searchHit);
}
public function testWithHits()
{
$this->searchResponse->shouldReceive('rewind')
->once()
->ordered();
$this->searchResponse->shouldReceive('current')
->andReturn(
[
'hits' => [
'hits' => [
[ 'foo' => 'bar0' ],
[ 'foo' => 'bar1' ],
[ 'foo' => 'bar2' ]
],
'total' => 3
]
],
[
'hits' => [
'hits' => [
[ 'foo' => 'bar0' ],
[ 'foo' => 'bar1' ],
[ 'foo' => 'bar2' ]
],
'total' => 3
]
],
[
'hits' => [
'hits' => [
[ 'foo' => 'bar0' ],
[ 'foo' => 'bar1' ],
[ 'foo' => 'bar2' ]
],
'total' => 3
]
],
[
'hits' => [
'hits' => [
[ 'foo' => 'bar0' ],
[ 'foo' => 'bar1' ],
[ 'foo' => 'bar2' ]
],
'total' => 3
]
],
[
'hits' => [
'hits' => [
[ 'foo' => 'bar3' ],
[ 'foo' => 'bar4' ]
],
'total' => 2
]
],
[
'hits' => [
'hits' => [
[ 'foo' => 'bar3' ],
[ 'foo' => 'bar4' ]
],
'total' => 2
]
]
);
$this->searchResponse->shouldReceive('valid')
->andReturn(true, true, true, false);
$this->searchResponse->shouldReceive('next')
->times(2)
->ordered();
$responses = new SearchHitIterator($this->searchResponse);
$i = 0;
foreach ($responses as $key => $value) {
$this->assertEquals($i, $key);
$this->assertEquals("bar$i", $value['foo']);
$i++;
}
}
}
PK ?V9X X I tests/Elasticsearch/Tests/Helper/Iterators/SearchResponseIteratorTest.phpnu W+A
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://Elasticsearch.org
*/
class SearchResponseIteratorTest extends \PHPUnit\Framework\TestCase
{
public function tearDown()
{
m::close();
}
public function testWithNoResults()
{
$search_params = [
'scroll' => '5m',
'index' => 'twitter',
'size' => 1000,
'body' => [
'query' => [
'match_all' => new \stdClass
]
]
];
$mock_client = m::mock(Client::class);
$mock_client->shouldReceive('search')
->once()
->ordered()
->with($search_params)
->andReturn(['_scroll_id' => 'scroll_id_01']);
$mock_client->shouldReceive('scroll')
->never();
$mock_client->shouldReceive('clearScroll')
->once()
->ordered()
->withAnyArgs();
$responses = new SearchResponseIterator($mock_client, $search_params);
$this->assertCount(0, $responses);
}
public function testWithHits()
{
$search_params = [
'scroll' => '5m',
'index' => 'twitter',
'size' => 1000,
'body' => [
'query' => [
'match_all' => new \stdClass
]
]
];
$mock_client = m::mock(Client::class);
$mock_client->shouldReceive('search')
->once()
->ordered()
->with($search_params)
->andReturn(
[
'_scroll_id' => 'scroll_id_01',
'hits' => [
'hits' => [
[
'foo' => 'bar'
]
]
]
]
);
$mock_client->shouldReceive('scroll')
->once()
->ordered()
->with(
[
'scroll_id' => 'scroll_id_01',
'scroll' => '5m'
]
)
->andReturn(
[
'_scroll_id' => 'scroll_id_02',
'hits' => [
'hits' => [
[
'foo' => 'bar'
]
]
]
]
);
$mock_client->shouldReceive('scroll')
->once()
->ordered()
->with(
[
'scroll_id' => 'scroll_id_02',
'scroll' => '5m'
]
)
->andReturn(
[
'_scroll_id' => 'scroll_id_03',
'hits' => [
'hits' => [
[
'foo' => 'bar'
]
]
]
]
);
$mock_client->shouldReceive('scroll')
->once()
->ordered()
->with(
[
'scroll_id' => 'scroll_id_03',
'scroll' => '5m'
]
)
->andReturn(
[
'_scroll_id' => 'scroll_id_04',
'hits' => [
'hits' => []
]
]
);
$mock_client->shouldReceive('scroll')
->never()
->with(
[
'scroll_id' => 'scroll_id_04',
'scroll' => '5m'
]
);
$mock_client->shouldReceive('clearScroll')
->once()
->ordered()
->withAnyArgs();
$responses = new SearchResponseIterator($mock_client, $search_params);
$count = 0;
$i = 0;
foreach ($responses as $response) {
$count += count($response['hits']['hits']);
$this->assertEquals($response['_scroll_id'], sprintf("scroll_id_%02d", ++$i));
}
$this->assertEquals(3, $count);
}
}
PK ?VDA <