Validator\Db\RecordExists with multiple columns - zend-framework2

ZF2 docs show the following example in terms of using Db\RecordExists validator with multiple columns.
$email = 'user#example.com';
$clause = $dbAdapter->quoteIdentifier('email') . ' = ' . $dbAdapter->quoteValue($email);
$validator = new Zend\Validator\Db\RecordExists(
array(
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
'exclude' => $clause
)
);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
I’ve tried this using my own Select object containing a more complex where condition. However, isValid() must be called with a value parameter.
In the example above $username is passed to isValid(). But there seems to be no according field definition.
I tried calling isValid() with an empty string, but this does not produce the desired result, since Zend\Validator\Db\AbstractDb::query() always adds the value to the statement:
$parameters = $statement->getParameterContainer();
$parameters['where1'] = $value;
If I remove the seconds line above, my validator produces the expected results.
Can someone elaborate on how to use RecordExists with the where conditions in my custom Select object? And only those?

The best way to do this is probably by making your own validator that extends one of Zend Framework's, because it doesn't seem like the (No)RecordExists classes were meant to handle multiple fields (I'd be happy to be proven wrong, because it'd be easier if they did).
Since, as you discovered, $parameters['where1'] is overridden with $value, you can deal with this by making sure $value represents what the value of the first where should be. In the case of using a custom $select, $value will replace the value in the first where clause.
Here's a hacky example of using RecordExists with a custom select and multiple where conditions:
$select = new Select();
$select->from('some_table')
->where->equalTo('first_field', 'value1') // this gets overridden
->and->equalTo('second_field', 'value2')
;
$validator = new RecordExists($select);
$validator->setAdapter($someAdapter);
// this overrides value1, but since isValid requires a string,
// the redundantly supplied value allows it to work as expected
$validator->isValid('value1');
The above produces the following query:
SELECT `some_table`.* FROM `some_table` WHERE `first_field` = 'value1' AND `second_field` = 'value2'
...which results in isValid returning true if there was a result.

Related

How to mock interface method to return the parameter value using closures

Sometimes it happens that we need to mock some method of the interface just to work and we do not really care what it will return, we just need to ensure it is called.
There is an approach to set
->expects(static::once())->method('someMethod')->willReturn('dumbValue');
But it is often necessary to see in the test with which parameter it was called, then we need to use
->expects(static::once())->method('someMethod')->with(static::equalTo('paramvalue'))->willReturn('dumbValue');
It gets longer and longer.
Is there an approach to return the parameter value that is given to the function mocked in willReturn() method?
It would be so simple to test the output with data provider then
We can use closures to process the callback.
$this->translator = $this->createMock(TranslatorInterface::class);
$this->translator->method('translate')->will(
$this->returnCallback(
function ($msgid) {
return (string)$msgid;
}
)
);
Also, we can return not only parameter value but any variable value, generated before:
$variable = 'hello'
$this->returnCallback(
function ($msgid) use $variable {
return $msgid . $variable;
}
)
and the assert will look like:
static::assertEquals(
'key',
$this->translator->translate('key');
);
static::assertEquals(
'some text and translated '. 'key',
'some text and translated ' . $this->translator->translate('key');
);

How do I query all documents in a Firestore collection for all strings in an array? [duplicate]

From the docs:
You can also chain multiple where() methods to create more specific queries (logical AND).
How can I perform an OR query?
Example:
Give me all documents where the field status is open OR upcoming
Give me all documents where the field status == open OR createdAt <= <somedatetime>
OR isn't supported as it's hard for the server to scale it (requires keeping state to dedup). The work around is to issue 2 queries, one for each condition, and dedup on the client.
Edit (Nov 2019):
Cloud Firestore now supports IN queries which are a limited type of OR query.
For the example above you could do:
// Get all documents in 'foo' where status is open or upcmoming
db.collection('foo').where('status','in',['open','upcoming']).get()
However it's still not possible to do a general OR condition involving multiple fields.
With the recent addition of IN queries, Firestore supports "up to 10 equality clauses on the same field with a logical OR"
A possible solution to (1) would be:
documents.where('status', 'in', ['open', 'upcoming']);
See Firebase Guides: Query Operators | in and array-contains-any
suggest to give value for status as well.
ex.
{ name: "a", statusValue = 10, status = 'open' }
{ name: "b", statusValue = 20, status = 'upcoming'}
{ name: "c", statusValue = 30, status = 'close'}
you can query by ref.where('statusValue', '<=', 20) then both 'a' and 'b' will found.
this can save your query cost and performance.
btw, it is not fix all case.
I would have no "status" field, but status related fields, updating them to true or false based on request, like
{ name: "a", status_open: true, status_upcoming: false, status_closed: false}
However, check Firebase Cloud Functions. You could have a function listening status changes, updating status related properties like
{ name: "a", status: "open", status_open: true, status_upcoming: false, status_closed: false}
one or the other, your query could be just
...where('status_open','==',true)...
Hope it helps.
This doesn't solve all cases, but for "enum" fields, you can emulate an "OR" query by making a separate boolean field for each enum-value, then adding a where("enum_<value>", "==", false) for every value that isn't part of the "OR" clause you want.
For example, consider your first desired query:
Give me all documents where the field status is open OR upcoming
You can accomplish this by splitting the status: string field into multiple boolean fields, one for each enum-value:
status_open: bool
status_upcoming: bool
status_suspended: bool
status_closed: bool
To perform your "where status is open or upcoming" query, you then do this:
where("status_suspended", "==", false).where("status_closed", "==", false)
How does this work? Well, because it's an enum, you know one of the values must have true assigned. So if you can determine that all of the other values don't match for a given entry, then by deduction it must match one of the values you originally were looking for.
See also
in/not-in/array-contains-in: https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any
!=: https://firebase.googleblog.com/2020/09/cloud-firestore-not-equal-queries.html
I don't like everyone saying it's not possible.
it is if you create another "hacky" field in the model to build a composite...
for instance, create an array for each document that has all logical or elements
then query for .where("field", arrayContains: [...]
you can bind two Observables using the rxjs merge operator.
Here you have an example.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/merge';
...
getCombinatedStatus(): Observable<any> {
return Observable.merge(this.db.collection('foo', ref => ref.where('status','==','open')).valueChanges(),
this.db.collection('foo', ref => ref.where('status','==','upcoming')).valueChanges());
}
Then you can subscribe to the new Observable updates using the above method:
getCombinatedStatus.subscribe(results => console.log(results);
I hope this can help you, greetings from Chile!!
We have the same problem just now, luckily the only possible values for ours are A,B,C,D (4) so we have to query for things like A||B, A||C, A||B||C, D, etc
As of like a few months ago firebase supports a new query array-contains so what we do is make an array and we pre-process the OR values to the array
if (a) {
array addObject:#"a"
}
if (b) {
array addObject:#"b"
}
if (a||b) {
array addObject:#"a||b"
}
etc
And we do this for all 4! values or however many combos there are.
THEN we can simply check the query [document arrayContains:#"a||c"] or whatever type of condition we need.
So if something only qualified for conditional A of our 4 conditionals (A,B,C,D) then its array would contain the following literal strings: #["A", "A||B", "A||C", "A||D", "A||B||C", "A||B||D", "A||C||D", "A||B||C||D"]
Then for any of those OR combinations we can just search array-contains on whatever we may want (e.g. "A||C")
Note: This is only a reasonable approach if you have a few number of possible values to compare OR with.
More info on Array-contains here, since it's newish to firebase docs
If you have a limited number of fields, definitely create new fields with true and false like in the example above. However, if you don't know what the fields are until runtime, you have to just combine queries.
Here is a tags OR example...
// the ids of students in class
const students = [studentID1, studentID2,...];
// get all docs where student.studentID1 = true
const results = this.afs.collection('classes',
ref => ref.where(`students.${students[0]}`, '==', true)
).valueChanges({ idField: 'id' }).pipe(
switchMap((r: any) => {
// get all docs where student.studentID2...studentIDX = true
const docs = students.slice(1).map(
(student: any) => this.afs.collection('classes',
ref => ref.where(`students.${student}`, '==', true)
).valueChanges({ idField: 'id' })
);
return combineLatest(docs).pipe(
// combine results by reducing array
map((a: any[]) => {
const g: [] = a.reduce(
(acc: any[], cur: any) => acc.concat(cur)
).concat(r);
// filter out duplicates by 'id' field
return g.filter(
(b: any, n: number, a: any[]) => a.findIndex(
(v: any) => v.id === b.id) === n
);
}),
);
})
);
Unfortunately there is no other way to combine more than 10 items (use array-contains-any if < 10 items).
There is also no other way to avoid duplicate reads, as you don't know the ID fields that will be matched by the search. Luckily, Firebase has good caching.
For those of you that like promises...
const p = await results.pipe(take(1)).toPromise();
For more info on this, see this article I wrote.
J
OR isn't supported
But if you need that you can do It in your code
Ex : if i want query products where (Size Equal Xl OR XXL : AND Gender is Male)
productsCollectionRef
//1* first get query where can firestore handle it
.whereEqualTo("gender", "Male")
.addSnapshotListener((queryDocumentSnapshots, e) -> {
if (queryDocumentSnapshots == null)
return;
List<Product> productList = new ArrayList<>();
for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {
Product product = snapshot.toObject(Product.class);
//2* then check your query OR Condition because firestore just support AND Condition
if (product.getSize().equals("XL") || product.getSize().equals("XXL"))
productList.add(product);
}
liveData.setValue(productList);
});
For Flutter dart language use this:
db.collection("projects").where("status", whereIn: ["public", "unlisted", "secret"]);
actually I found #Dan McGrath answer working here is a rewriting of his answer:
private void query() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("STATUS")
.whereIn("status", Arrays.asList("open", "upcoming")) // you can add up to 10 different values like : Arrays.asList("open", "upcoming", "Pending", "In Progress", ...)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
// I assume you have a model class called MyStatus
MyStatus status= documentSnapshot.toObject(MyStatus.class);
if (status!= null) {
//do somthing...!
}
}
}
});
}

Adding new Mantis status but ran out of enumeration values

I was wondering if you had any thoughts about this issue: We want to add one more status at a specific 'place' between two statuses, but we ran out of enumeration for it.
The enumeration looks like this:
$s_status_enum_string = "10:new,20:feedback,40:confirmed,50:assigned,52:in progress,53:code review pending,54:merge pending, 56:merged, 58:resolved, 60:testing, 70:tested, 90:closed, 91:updating test documentation";
And I want to add a new status between 52 and 53 so that, on the pull-down menu for status, they appear in the desired order.
I tried different things - including changing the .php file definitions then updating the MySQL table's status field in mantis_bug_table, but it messes up all the views and filters.
Any ideas?
The following steps might help you:
Redefine the enumeration string as per your requirements
Prepare a traceability with your current enumeration values
Update the status field in bugs table with the new values
Add the enumeration in config.php
You may have to reset your previous filters. The filter criteria is stored as a serialized string and it's very difficult to modify.
If anyone is having issues with this you need to change the following:
In config_inc.php modify $g_status_enum_string to ennumerate the new statuses as you see fit.
In custom_constants_inc.php make sure to do the same as above.
In the database, run SQL commands such as this:
UPDATE mantisclone.mantis_bug_table SET status=100 WHERE status=10;
to change the actual records for existing status IDs to new ones.
In custom_strings_inc.php modify $s_status_enum_string and input your new statuses. For example one of mine was:
$s_sanity_test_bug_title = "Set Issue Sanity Test";
$s_sanity_test_bug_button = "Issue Sanity Test Pending";
$s_email_notification_title_for_sanity_test = "The following issue is NOW SANITY TEST PENDING";
Finally you'll need a small script to change the existing ennumerated values in mantis_filters_table. This was mine, alter it as you see fit:
<?php
$mantisDB="myMantisDatabaseName";
mysql_connect("localhost", "XXXX", "YYYY") or die("Could not connect: " . mysql_error());
mysql_select_db($mantisDB);
$result = mysql_query("SELECT id, filter_string FROM $mantisDB.mantis_filters_table");
function parseRecord($statusArray)
{
$newStatus = array( "10" => "100",
"20" => "200",
"50" => "300",
"52" => "400",
"53" => "500",
"54" => "540",
"56" => "560",
"58" => "580",
"60" => "600",
"70" => "700",
"75" => "450",
"90" => "900",
"91" => "910"
);
foreach ($statusArray as $key=>$value)
{
if(array_key_exists($value, $newStatus))
{
echo "Found value $value, replacing it with " . $newStatus[$value] . "\n";
$statusArray[$key] = (int)$newStatus[$value];
}
}
}
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$statusID = $row["id"];
$serializedString = $row["filter_string"];
$unserializedArray = unserialize(substr($serializedString,3)); // There's a prepended 'v8#' string in there, don't know why.
parseRecord(&$unserializedArray["hide_status"]);
parseRecord(&$unserializedArray["show_status"]);
$newSerialized = "v8#".serialize($unserializedArray);
// echo $newSerialized;
$changeStatus = mysql_query("UPDATE $mantisDB.mantis_filters_table SET filter_string='$newSerialized' WHERE id=$statusID");
}
mysql_free_result($result);
?>
I hope this works, let me know if you're having any issues.

ZF2 Db\RecordExists - Check additional columns

I have a problem with ZF2 RecordExists method. I will explain my problematic case/scenario.
Table: users
Columns: id, emailaddress, websitename
Sample Records:
1, user1#email.com, 1site.com
2, user2#email.com, 1site.com
3, user3#email.com, 2site.com
4, user4#email.com, 2site.com
5, user5#email.com, 1site.com
6, user6#email.com, 3site.com
7, user7#email.com, 4site.com
I am using the following snippet for already exist condition.
//Check that the email address exists in the database
$validator = new Zend\Validator\Db\RecordExists(
array(
'table' => 'users',
'field' => 'emailaddress'
)
);
if ($validator->isValid($emailaddress)) {
// email address appears to be valid
} else {
// email address is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
As per the above snippets, user1#email.com cannot register again. Because, that emailaddress is exist in table.
But, i would like to do register with 2site.com. Because, user1#email.com is in 1site.com.
So, user1#email.com cannot register with 1site.com again. But, user1#email.com can register with 2site.com.
How is it possible? Let me know your suggestions.
There are two way to do this.
First using Excluding Record methods
Where you exclude the record of websitename field value.
Zend\Validator\Db\RecordExists and Zend\Validator\Db\NoRecordExists
also provide a means to test the database, excluding a part of the
table, either by providing a where clause as a string, or an array
with the keys “field” and “value”.
$email = 'user#example.com';
$clause = $db->quoteInto('email = ?', $email);
$validator = new Zend\Validator\Db\RecordExists(
array(
'table' => 'users',
'field' => 'username',
'exclude' => $clause
)
);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
Second by writing your own custom validtor.
You need to extend AbstractDB class and create your own class on directions of RecordExists Class. In your own cust class your can define your own query and pass it to isValid function.
I have created a Custom Validator oposite to Exclude, which is include.
include is reserve word, Now sure if it will work.
check it here
More readings on this
Guidlines 1
Please have look to existing validtor for creating your own custom validatorCustom validator guildline
Chain validator 2

Getting a list of distinct entities projected into a new type with extra field for the count

I'm designing an interface where the user can join a publicaiton to a keyword, and when they do, I want to suggest other keywords that commonly occur in tandem with the selected keyword. The trick is getting the frequency of correlation alongside the properties of the suggested keywords.
The Keyword type (EF) has these fields:
int Id
string Text
string UrlString
...and a many-to-many relation to a Publications entity-set.
I'm almost there. With :
var overlappedKeywords =
selectedKeyword.Publications.SelectMany(p => p.Keywords).ToList();
Here I get something very useful: a flattened list of keywords, each duplicated in the list however many times it appears in tandem with selectedKeyword.
The remaining Challenge:
So I want to get a count of the number of times each keyword appears in this list, and project the distinct keyword entities onto a new type, called KeywordCounts, having the same fields as Keyword but with one extra field: int PublicationsCount, into which I will populate the count of each Keyword within overlappedKeywords. How can I do this??
So far I've tried 2 approaches:
var keywordCounts = overlappingKeywords
.Select(oc => new KeywordCount
{
KeywordId = oc.Id,
Text = oc.Text,
UrlString = oc.UrlString,
PublicationsCount = overlappingKeywords.Count(ok2 => ok2.Id == oc.Id)
})
.Distinct();
...PublicationsCount is getting populated correctly, but Distinct isn't working here. (must I create an EqualityComarer for this? Why doesn't the default EqualityComarer work?)
var keywordCounts = overlappingKeywords
.GroupBy(o => o.Id)
.Select(c => new KeywordCount
{
Id = ???
Text = ???
UrlString = ???
PublicationsCount = ???
})
I'm not very clear on GroupBy. I don't seem to have any access to 'o' in the Select, and c isn't comping up with any properties of Keyword
UPDATE
My first approach would work with a simple EqualityComparer passed into .Distinct() :
class KeywordEqualityComparer : IEqualityComparer<KeywordCount>
{
public bool Equals(KeywordCount k1, KeywordCount k2)
{
return k1.KeywordId== k2.KeywordId;
}
public int GetHashCode(KeywordCount k)
{
return k.KeywordId.GetHashCode();
}
}
...but Slauma's answer is preferable (and accepted) because it does not require this. I'm still stumped as to what the default EqualityComparer would be for an EF entity instance -- wouldn't it just compare based on primary ids, as I did above here?
You second try is the better approach. I think the complete code would be:
var keywordCounts = overlappingKeywords
.GroupBy(o => o.Id)
.Select(c => new KeywordCount
{
Id = c.Key,
Text = c.Select(x => x.Text).FirstOrDefault(),
UrlString = c.Select(x => x.UrlString).FirstOrDefault(),
PublicationsCount = c.Count()
})
.ToList();
This is LINQ to Objects, I guess, because there doesn't seem to be a EF context involved but an object overlappingKeywords, so the grouping happens in memory, not in the database.

Resources