Skip to content

Commit 1965904

Browse files
Feature/generate from version 1.211.0 (#42)
* Skip flaky test * Update relewise client to 1.211.0 * Generated the new moddels * Updated the search hightlight test to use the new model * Single is a float not an int * Floats instead of ints * Date time should be handled like date time * A struct is also a value type so we should not go into this if when type is struct * Also handle key value pair generically * new models after hydration changes * Add a test proving recently purchased facet not working * Add a non generated time span * Do not use depricated stuff * Make custom types more generic * Optional generic lists cannot have a defualt value * new recently purches facet model * rename test * Override chosen constructor for `FieldIndexConfiguration`. * Updated unit test to fit old constructor again. * Review comments * Remove timespan * Rename test --------- Co-authored-by: KSGRelewise <KSGRelewise@users.noreply.github.com>
1 parent 836b8c3 commit 1965904

File tree

51 files changed

+1433
-78
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+1433
-78
lines changed

Generator/Generator.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
<ItemGroup>
1111
<PackageReference Include="AngleSharp.Xml" Version="1.0.0" />
12-
<PackageReference Include="Relewise.Client" Version="1.193.0" />
12+
<PackageReference Include="Relewise.Client" Version="1.211.0" />
1313
</ItemGroup>
1414

1515
</Project>

Generator/PhpMemberWriters/PhpCreatorMethodWriter.cs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
using System.CodeDom.Compiler;
33
using System.Globalization;
44
using System.Reflection;
5+
using Relewise.Client.DataTypes.Search.Configuration;
6+
using Relewise.Client.DataTypes.Search.Configuration.Parsers;
57
using Relewise.Client.Requests;
68
using Relewise.Client.Requests.RelevanceModifiers;
79
using Relewise.Client.Requests.Conditions;
@@ -24,6 +26,10 @@ public class PhpCreatorMethodWriter
2426
[typeof(ProductRecentlyViewedByUserRelevanceModifier)] = typeof(ProductRecentlyViewedByUserRelevanceModifier).GetConstructor(new[] { typeof(DateTimeOffset), typeof(double), typeof(double) })!,
2527
// For backwards compatibility remove in next major release.
2628
[typeof(VariantDataRelevanceModifier)] = typeof(VariantDataRelevanceModifier).GetConstructor(new[] { typeof(string), typeof(List<ValueCondition>), typeof(ValueSelector), typeof(bool), typeof(bool) })!,
29+
// For backwards compatibility remove in next major release.
30+
#pragma warning disable CS0618 // Type or member is obsolete
31+
[typeof(FieldIndexConfiguration)] = typeof(FieldIndexConfiguration).GetConstructor(new[] { typeof(bool), typeof(byte), typeof(PredictionSourceType), typeof(Parser), typeof(MatchTypeSettings) })!,
32+
#pragma warning restore CS0618 // Type or member is obsolete
2733
};
2834

2935
/// <summary>
@@ -281,7 +287,28 @@ public void Write(IndentedTextWriter writer, Type type, string typeName,
281287

282288
private string DefaultValueSetter(ParameterInfo parameter)
283289
{
284-
return parameter.HasDefaultValue && parameter.DefaultValue is null ? " = Null" : parameter.DefaultValue is { } defaultValue && (defaultValue.GetType().IsValueType || defaultValue is string) ? $" = {LiteralValueExpression(defaultValue)}" : "";
290+
bool isGenericList = parameter.ParameterType.IsGenericType
291+
&& parameter.ParameterType.GetGenericTypeDefinition() == typeof(List<>)
292+
&& parameter.ParameterType.GenericTypeArguments is [_];
293+
294+
if (parameter.HasDefaultValue && parameter.DefaultValue is null)
295+
{
296+
// Optional generic lists cannot have a default value
297+
if (isGenericList && parameter.IsOptional)
298+
{
299+
return "";
300+
}
301+
302+
return " = Null";
303+
}
304+
305+
if (parameter.DefaultValue is { } defaultValue &&
306+
(defaultValue.GetType().IsValueType || defaultValue is string))
307+
{
308+
return $" = {LiteralValueExpression(defaultValue)}";
309+
}
310+
311+
return "";
285312
}
286313

287314
private string LiteralValueExpression(object obj)

Generator/PhpMemberWriters/PhpHydrationMethodsWriter.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,23 @@ private string HydrationExpression(Type type, string jsonValue)
141141
{
142142
return $"{phpWriter.PhpTypeName(type)}::from({jsonValue})";
143143
}
144-
if (type == typeof(DateTimeOffset))
144+
if (type == typeof(DateTimeOffset) || type == typeof(DateTime))
145145
{
146146
return $"new DateTime({jsonValue})";
147147
}
148-
if (type.IsValueType || type == typeof(string) || type == typeof(Guid) || type == typeof(object) || type.IsArray || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(Dictionary<,>))))
148+
if (type == typeof(TimeSpan))
149+
{
150+
return $"DateIntervalFactory::fromTimeSpanString({jsonValue})";
151+
}
152+
if (type.IsPrimitive ||
153+
type == typeof(string) ||
154+
type == typeof(Guid) ||
155+
type == typeof(object) ||
156+
type == typeof(decimal) ||
157+
type.IsArray ||
158+
(type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) ||
159+
type.GetGenericTypeDefinition() == typeof(Dictionary<,>) ||
160+
type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))))
149161
{
150162
return jsonValue;
151163
}

Generator/PhpTypeResolver.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ public PhpTypeResolver(Assembly assembly)
1919
public string ResolveType(Type type) => type.Name switch
2020
{
2121
"String" or "Guid" => "string",
22-
"Int32" or "Int64" or "UInt16" or "Single" or "Byte" => "int",
23-
"Float" or "Double" or "Decimal" => "float",
22+
"Int32" or "Int64" or "UInt16" or "Byte" => "int",
23+
"Float" or "Double" or "Decimal" or "Single" => "float",
2424
"Boolean" => "bool",
2525
"Object" => "mixed",
2626
"DateTimeOffset" or "DateTime" => "DateTime",
27+
"TimeSpan" => "DateInterval",
2728
var value when value.StartsWith("Nullable") => $"?{ResolveType(type.GetGenericArguments()[0])}",
2829
var value when value.StartsWith("List") || value.StartsWith("Dictionary") || value.EndsWith("[]") || value.StartsWith("IEnumerable") => AddCollectionTypeDefinition(type),
2930
_ when type.IsGenericType => GetGenericTypeDefinition(type),
@@ -55,7 +56,7 @@ private static string GetTypeName(Type type)
5556
while (typeToPrependToName is not null)
5657
{
5758
name = typeToPrependToName.Name + name;
58-
59+
5960
typeToPrependToName = typeToPrependToName.DeclaringType;
6061
}
6162

@@ -131,4 +132,4 @@ private string GetGenericTypeDefinition(Type type)
131132
}
132133
return ResolveType(derivedTypes.First());
133134
}
134-
}
135+
}

Generator/PhpTypeWriters/PhpClassWriter.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,15 @@ public class PhpClassWriter : IPhpTypeWriter
1111
private static readonly Type[] ExtractableFacetResultTypes = { typeof(ProductFacetResult), typeof(ContentFacetResult), typeof(ProductCategoryFacetResult) };
1212
private static readonly string[] IgnoredProperties = new[] { "Channel", "SubChannel", "TrackingNumber" };
1313

14+
private static readonly Dictionary<string, string[]> TypesWithCustomUsings = new()
15+
{
16+
{ "DateInterval",
17+
[
18+
"use DateInterval;",
19+
@"use Relewise\Factory\DateIntervalFactory;"
20+
]
21+
}
22+
};
1423
private readonly PhpWriter phpWriter;
1524

1625
public PhpClassWriter(PhpWriter phpWriter)
@@ -70,6 +79,22 @@ public void Write(IndentedTextWriter writer, Type type, string typeName)
7079
if (hasDateTimeOrDateTimeOffsetProperty)
7180
{
7281
writer.WriteLine("use DateTime;");
82+
}
83+
84+
IEnumerable<string?> customUsings = gettableProperties
85+
.SelectMany(p => TypesWithCustomUsings.GetValueOrDefault(p.propertyTypeName) ?? [])
86+
.Distinct();
87+
88+
foreach (string? customUsing in customUsings)
89+
{
90+
if (customUsing != null)
91+
{
92+
writer.WriteLine(customUsing);
93+
}
94+
}
95+
96+
if (hasDateTimeOrDateTimeOffsetProperty)
97+
{
7398
writer.WriteLine("use JsonSerializable;");
7499
writer.WriteLine();
75100
}
@@ -168,4 +193,4 @@ public void Write(IndentedTextWriter writer, Type type, string typeName)
168193
{
169194
return (info, propertyTypeName: phpWriter.PhpTypeName(info), propertyName: info.Name, lowerCaseName: info.Name.ToCamelCase());
170195
}
171-
}
196+
}

src/Factory/DateIntervalFactory.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php declare(strict_types=1);
2+
namespace Relewise\Factory;
3+
4+
use DateInterval;
5+
use InvalidArgumentException;
6+
7+
class DateIntervalFactory {
8+
public static function fromTimeSpanString(string $timeSpanString) {
9+
10+
// Match [days.]hh:mm:ss[.fffffff]
11+
if (!preg_match('/^(?:(\d+)\.)?(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?$/', $timeSpanString, $m)) {
12+
throw new InvalidArgumentException("Invalid TimeSpan format: '$timeSpanString'");
13+
}
14+
15+
$days = isset($m[1]) ? (int)$m[1] : 0;
16+
$hours = ($days * 24) + (int)$m[2];
17+
$minutes = (int)$m[3];
18+
$seconds = (int)$m[4];
19+
$fraction = isset($m[5]) ? $m[5] : '0';
20+
21+
// Pad/truncate to 6 digits for microseconds
22+
$microseconds = (int)str_pad(substr($fraction, 0, 6), 6, '0');
23+
24+
return DateInterval::createFromDateString("$hours hours + $minutes minutes + $seconds seconds + $microseconds microseconds");
25+
}
26+
}

src/Models/Campaign.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ class Campaign extends CampaignEntityStateCampaignMetadataValuesRetailMediaEntit
1111
public string $advertiserId;
1212
public Budget $budget;
1313
public CampaignStatusWithHistory $status;
14+
public ?CampaignCampaignConditions $conditions;
1415

1516
public static function create(?string $id, CampaignEntityState $state, string $name, string $advertiserId, Budget $budget, ?ISchedule $schedule, PromotionCollection $promotions) : Campaign
1617
{
@@ -52,6 +53,10 @@ public static function hydrate(array $arr) : Campaign
5253
{
5354
$result->status = CampaignStatusWithHistory::hydrate($arr["status"]);
5455
}
56+
if (array_key_exists("conditions", $arr))
57+
{
58+
$result->conditions = CampaignCampaignConditions::hydrate($arr["conditions"]);
59+
}
5560
return $result;
5661
}
5762

@@ -91,6 +96,12 @@ function setStatus(CampaignStatusWithHistory $status)
9196
return $this;
9297
}
9398

99+
function setConditions(?CampaignCampaignConditions $conditions)
100+
{
101+
$this->conditions = $conditions;
102+
return $this;
103+
}
104+
94105
function setState(CampaignEntityState $state)
95106
{
96107
$this->state = $state;

src/Models/CampaignAnalyticsProductAnalytics.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public static function hydrate(array $arr) : CampaignAnalyticsProductAnalytics
2828
$result->timeSeries = array();
2929
foreach($arr["timeSeries"] as &$value)
3030
{
31-
array_push($result->timeSeries, $value);
31+
array_push($result->timeSeries, CampaignAnalyticsProductAnalyticsPeriodMetrics::hydrate($value));
3232
}
3333
}
3434
if (array_key_exists("promotions", $arr))
@@ -40,7 +40,7 @@ public static function hydrate(array $arr) : CampaignAnalyticsProductAnalytics
4040
$result->promotedProducts = array();
4141
foreach($arr["promotedProducts"] as &$value)
4242
{
43-
array_push($result->promotedProducts, $value);
43+
array_push($result->promotedProducts, CampaignAnalyticsProductAnalyticsPromotedProductMetrics::hydrate($value));
4444
}
4545
}
4646
return $result;

src/Models/CampaignAnalyticsProductAnalyticsPeriodMetrics.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public static function hydrate(array $arr) : CampaignAnalyticsProductAnalyticsPe
4343
$result->currencies = array();
4444
foreach($arr["currencies"] as &$value)
4545
{
46-
array_push($result->currencies, $value);
46+
array_push($result->currencies, CampaignAnalyticsProductAnalyticsPeriodMetricsCurrencyMetrics::hydrate($value));
4747
}
4848
}
4949
return $result;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Relewise\Models;
4+
5+
class CampaignCampaignConditions extends RetailMediaConditions
6+
{
7+
public string $typeDefinition = "Relewise.Client.DataTypes.RetailMedia.Campaign+CampaignConditions, Relewise.Client";
8+
public ?RetailMediaSearchTermConditionCollection $searchTerm;
9+
10+
public static function create() : CampaignCampaignConditions
11+
{
12+
$result = new CampaignCampaignConditions();
13+
return $result;
14+
}
15+
16+
public static function hydrate(array $arr) : CampaignCampaignConditions
17+
{
18+
$result = RetailMediaConditions::hydrateBase(new CampaignCampaignConditions(), $arr);
19+
if (array_key_exists("searchTerm", $arr))
20+
{
21+
$result->searchTerm = RetailMediaSearchTermConditionCollection::hydrate($arr["searchTerm"]);
22+
}
23+
return $result;
24+
}
25+
26+
function setSearchTerm(?RetailMediaSearchTermConditionCollection $searchTerm)
27+
{
28+
$this->searchTerm = $searchTerm;
29+
return $this;
30+
}
31+
}

0 commit comments

Comments
 (0)