<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Grzegorz Lasak (Gregster) on Medium]]></title>
        <description><![CDATA[Stories by Grzegorz Lasak (Gregster) on Medium]]></description>
        <link>https://medium.com/@bluznierca1?source=rss-8a2d31b5e9a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CN0zBzfUwy96fyxD5BUPyA.jpeg</url>
            <title>Stories by Grzegorz Lasak (Gregster) on Medium</title>
            <link>https://medium.com/@bluznierca1?source=rss-8a2d31b5e9a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:41:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bluznierca1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Golang mocked Enums validation on Struct]]></title>
            <link>https://medium.com/@bluznierca1/golang-mocked-enums-validation-on-struct-13a2c3fead0d?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/13a2c3fead0d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 19:34:08 GMT</pubDate>
            <atom:updated>2024-11-06T19:34:08.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I would like to present my approach towards validating so-called ‘Enums’ in Golang.</p><p>As we know, there is no GO language construct allowing defining Enums, which means we have to kind of mock their behaviour.</p><p>Unfortunately, that mocking also does not make it easy to validate provided value in some specific circumstances — one of them I just encountered and found a way to solve it.</p><h3>Problem description</h3><p>Application I am working on implements versioning which causes different acceptable values per version — usually next version extends previous one.</p><p>For each version, we have fixed types we can save which also means we have to validate incoming requests against these values.</p><p>For strong-typing, we implement so-called ‘Enums’ which have listed values they can accept.</p><p>We are using great library for validating struct values (which can be found <a href="https://github.com/go-playground/validator"><strong>HERE</strong></a><strong>). </strong>We could use rule oneof and list all possible options per struct but that forces us to update both ‘Enum’ types and validation rules (if the same value is added for both versions, then we have 3 places). Also, we need function on a given ‘Enum’ type which will allow to validate provided value in any place in the code (which is quite handy).</p><p>Since it was too much hustle, I came up with making sure we can validate struct’s value by the function implemented on ‘Enum’ and have the same function accessible on the type, so we can use it everywhere we need.</p><h3>Example of Solution</h3><p>I am keeping everything in one package for sake of simplicity of example.</p><pre>package validator<br><br>// Our interface that &#39;Enums&#39; will need to implement<br>type IValidatableEnum interface {<br> Valid() bool<br>}<br><br>// First &#39;Enum&#39;<br>type MyFirstType string<br>const (<br> First MyFirstType = &quot;First&quot;<br>)<br><br>// MyFirstType implementation of Valid() function<br>func (f MyFirstType) Valid() bool {<br> switch f { // for extending in future...<br> case First:<br>  return true<br> }<br> <br> return false<br>}<br><br>// MySecondType implementation of Valid() function<br>type MySecondType string<br>const (<br> Second MySecondType = &quot;Second&quot;<br>)<br><br>func (s MySecondType) Valid() bool {<br> switch s { // for extending in future...<br> case Second:<br>  return true<br> }<br> return false<br>}<br><br>type TempRequestObject struct {<br> First  MyFirstType  `json:&quot;first&quot; validate:&quot;validate_enum&quot;`<br> Second MySecondType `json:&quot;second&quot; validate:&quot;validate_enum&quot;`<br>}</pre><p>Here we have:</p><ul><li>IValidatableEnum which is our interface expecting Valid method to be implemented in order to be fulfilled</li><li>MyFirstType and MySecondType which are our ‘mocked’ Enums with their types (const)</li><li>TempRequestObject which is a struct expecting params with types of our ‘Enums’. json tag is for JSON naming and validate is for mentioned package to be able to validate value against provided rules</li></ul><p><strong>Let’s look at our Validator</strong></p><pre>package validator<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/go-playground/validator/v10&quot; // validating package<br> &quot;sync&quot;<br>)<br><br>var (<br> validate      *validator.Validate<br> validatorOnce sync.Once<br>)<br><br>func GetValidator() *validator.Validate {<br> validatorOnce.Do(func() {<br>  validate = validator.New()<br>  _ = validate.RegisterValidation(&quot;validate_enum&quot;, validateEnum)<br> })<br><br> return validate<br>}<br><br>func validateEnum(fl validator.FieldLevel) bool {<br> field := fl.Field()<br><br> if field.CanInterface() {<br>  if validatable, ok := field.Interface().(IValidatableEnum); ok {<br>   return validatable.Valid()<br>  }<br> }<br><br>// if field not implementing IValidatableEnum, fail validation<br> return false<br>}</pre><p><strong>What happens here:</strong></p><ol><li>We have validator which gets instantiated only once (can be omitted, it won’t influence functionality)</li><li>We register custom validation rule validate_enum which can be used in our list of validation rules on Struct tags (previous code)</li><li>We define function validateEnumwhich checks if provided field type implements desired interface ValidatableEnum and then it triggers Valid function on our value to check if it will pass the check.<br>In case the field does not implement that interface, we fail the validation.</li></ol><p><strong>Usage</strong></p><pre> validate := validator.GetValidator()<br> tempReq := &amp;validator.TempRequestObject{<br>  First:  &quot;invalid value&quot;,<br>  Second: Second,<br> }<br><br>err = validate.Struct(tempReq)<br>if err != nil {<br>log.Fatalf(&quot;validate.Struct(); err = %v&quot;, err)<br>}</pre><ol><li>We get instance of our validator already containing custom rule validate_enum</li><li>We build the struct with values (in reality it would be Unmarshalling incoming request JSON)</li><li>We trigger validation</li></ol><p><strong>Current validation will fail.</strong></p><p>It is because TempRequestObject.First has wrong value (which without triggering Valid function would be fine!)</p><p>Side Note: TempRequestObject.First with value “invalid value&quot; would not trigger any error because our MyFirstType is of type string …</p><p>TempRequestObject.Second would pass because it uses valid value.</p><p><strong>Below Structs would pass (using const in the same package for values):</strong></p><pre>tempReq := &amp;validator.TempRequestObject{<br>  First:  First,<br>  Second: validator.Second,<br> }</pre><p><strong>As well as that one would pass, too (because these values are listed as Valid):</strong></p><pre>tempReq := &amp;validator.TempRequestObject{<br>  First:  &quot;First&quot;,<br>  Second: &quot;Second&quot;,<br> }</pre><p>If you define Field’s Type to be ‘Enum’ that does not implement Valid function, it will fail on validation.</p><p>I hope that simple example will make your life easier in case you encountered the same problem.</p><p>Greetings</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13a2c3fead0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang with Chi + Swagger (OpenAPI) Testing]]></title>
            <link>https://medium.com/@bluznierca1/golang-withchi-swagger-openapi-testing-f17a2e7c069c?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17a2e7c069c</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[chi]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 17:29:08 GMT</pubDate>
            <atom:updated>2024-10-01T06:08:30.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Juuign_L-O0utbOrV60NIw.jpeg" /></figure><p>Hi,</p><p><strong>I believe we can all agree that:</strong></p><ul><li>Testing our applications is important.</li><li>Documenting our API is important.</li><li>Making it simple is beneficial.</li></ul><p>I would like to share with you the setup I came up with lately which helped me to implement all 3 above points in Web API project using Golang with Chi and Swagger (OpenAPI).</p><h3>Prerequisities</h3><ul><li>Already existing Golang repo with imported Chi router and registered routes. Setting it up is not part of this article BUT you can find repository with sample code for that article <a href="https://github.com/bluznierca1/go-chi-swagger-testing"><strong>HERE</strong></a></li><li>Config file for your Swagger docs (can be JSON or YML, both will work fine). BTW, you can test your file at: <a href="https://editor.swagger.io/">https://editor.swagger.io/</a><br>Sample file used for that article can be found <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/internal/utils/misc/openapi.yml"><strong>HERE</strong></a></li></ul><h3>What are we creating?</h3><ol><li>Tests helper for OpenAPI/Swagger specifically.<br>We are about to have wrappers for <a href="https://github.com/getkin/kin-openapi/">https://github.com/getkin/kin-openapi/</a> package (great one!) which helps to parse and work with config files.</li><li>Testing if all endpoints and their methods defined in OpenAPI config file are registered in our Chi router.</li><li>Testing if all endpoints and their methods defined on Chi router are defined in OpenAPI config file.</li><li>Testing our handlers behaviour against their definitions inside our OpenAPI config file. That includes responses, headers, status codes.</li></ol><h3>Let’s start with our OpenAPI tests helper</h3><p><strong>Before we go through the end version of our helper, we will go through functions we will need . Final version of the file will be available at the end of that paragraph.</strong></p><p>At the beginning, we create structs that will hold our paths’ data which we will need soon for our checks:</p><pre>// Details of the endpoint defined in OpenApi file<br>type OpenApiPathDetails struct {<br> Method        string<br> // details from our OpenAPI config file for that path<br> PathOperation *openapi3.Operation<br>}<br><br>// RouterPathDetails details of the path defined on Router<br>type RouterPathDetails struct {<br> Method string<br>}</pre><p>Now we need a struct that will hold all needed data for our request that we will test. It will be used gather all following info:</p><ul><li><strong>HttpReq </strong>Our mocked request containing path, method and body <strong>()</strong></li><li><strong>OpenApiDoc</strong> Our OpenAPI config file which is already loaded via package we use</li><li><strong>RequestValidationOptions </strong>all options that we need to use when checking our *http.Request against request data defined in our OpenAPI config file (f.ex. excluding authentication,skipping validation of body etc.)</li><li><strong>ResponseValidationOptions </strong>all options that we need to use when checking our received Response against response definition in OpenAPI for the path we used in HttpReq</li><li><strong>HandlerCallback </strong>crucial piece — it is a handler function for our endpoint.</li><li><strong>ExpectedBodySubstring </strong>a string that will be expected to be in response body. When that is empty string, no checks in place. You can check both substring or whole string because there is used<strong> strings.Contains()</strong> function</li></ul><pre>// OpenApiTestRequestData struct holding all required parameters for testing endpoints<br>// including request, special options (f.ex. for excluding some checks), options for validation response,<br>// and endpoint handler callback<br>type OpenApiTestRequestData struct {<br> // HttpReq - your *http.Request. Build it in your test and deliver. You can attach context, too.<br> HttpReq *http.Request<br><br> // Document needs to be scanned before and delivered to keep flexibility<br> OpenApiDoc *openapi3.T<br><br> // Options for Request Validation for controlling of what gets tested<br> RequestValidationOptions *openapi3filter.Options<br><br> // Options for Response Validation for controlling of what gets tested<br> ResponseValidationOptions *openapi3filter.Options<br><br> // Your Handler code to mock endpoint&#39;s behaviour<br> HandlerCallback func(w http.ResponseWriter, r *http.Request)<br><br> // String that is expected to appear in response. Empty string skips check<br> ExpectedBodySubstring string<br>}</pre><p>We need to define our function for loading OpenAPI config file via external package we use:</p><pre>// LoadOpenApiYmlFile load OpenApi yaml/json file<br>//<br>// Instead of log.Fatalf(), you can transform function to return error and handle it further<br>// In here, when file not found, no point of executing further tests.<br>func LoadOpenApiConfigFile() *openapi3.T {<br> loader := openapi3.NewLoader()<br><br> // I recommend updating it to absolute path with ENV vars...<br> doc, err := loader.LoadFromFile(&quot;{YOUR_ABSOLUTE_PATH_GOES_HERE}&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed load swagger spec: %v&quot;, err)<br> }<br><br> return doc<br>}</pre><p>Helper function which will gather all paths (with methods) and their definitions in our OpenAPI config file:</p><pre>// GetOpenApiPathsData - builds a map with all routes and their details<br>//<br>// # It is loaded from config file for OpenApi<br>//<br>// If (for method) `PathOperation == nil` that means there is no route defined<br>//<br>// # Params:<br>//<br>// - openApiDoc: *openapi3.T<br>//<br>// # Returns:<br>//<br>// - map[string][]OpenApiPathDetails<br>func GetOpenApiPathsData(openApiDoc *openapi3.T) map[string][]OpenApiPathDetails {<br> openApiPaths := map[string][]OpenApiPathDetails{}<br><br> // build paths data from OpenAPI<br> for path, pathItem := range openApiDoc.Paths.Map() {<br>  openApiPaths[path] = []OpenApiPathDetails{<br>   {Method: http.MethodGet, PathOperation: pathItem.Get},<br>   {Method: http.MethodPut, PathOperation: pathItem.Put},<br>   {Method: http.MethodDelete, PathOperation: pathItem.Delete},<br>   {Method: http.MethodPost, PathOperation: pathItem.Post},<br>   {Method: http.MethodPatch, PathOperation: pathItem.Patch},<br>  }<br> }<br><br> return openApiPaths<br>}</pre><p>Since we have all paths from our OpenAPI config file, now we need to gather all paths from our Router:</p><pre>// GetRouterPathsData - builds a map with all routes and their methods<br>//<br>// # Params:<br>//<br>// - router: *chi.Mux<br>//<br>// # Returns:<br>//<br>// - map[string][]RouterPathDetails<br>//<br>// - error<br>func GetRouterPathsData(router *chi.Mux) (map[string][]RouterPathDetails, error) {<br> routerPaths := map[string][]RouterPathDetails{}<br> err := chi.Walk(router, func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {<br>  routerPaths[route] = append(routerPaths[route], RouterPathDetails{Method: method})<br>  return nil<br> })<br><br> return routerPaths, err<br>}</pre><p>For easier operating on our parsed OpenAPI routes, we create a custom router provided by ‘kin-openapi’ package:</p><pre>func NewOpenApiRouter(openApiDoc *openapi3.T) (routers.Router, error) {<br> return gorillamux.NewRouter(openApiDoc)<br>}</pre><p>Now, it is time for main function responsible for testing mocked requests with provided handler against OpenAPI schema.</p><pre>// OpenApiTestRequest - perform full test of request against OpenApi Document:<br>//<br>// 1. Test request body before sending it to endpoint (possible control via testData.testData.RequestValidationOptions)<br>//<br>// 2. Mock server and serve endpoint with provided handler<br>//<br>// 3. Test received response<br>//<br>// # Options<br>//<br>// Both request and response objects take Options as parameter, so you can control behaviour of this test.<br>//<br>// # Params<br>//<br>// testData: OpenApiTestRequestData<br>//<br>// # Returns<br>//<br>// - error: in case something fails. You can use it to fail test<br>func OpenApiTestRequest(testData OpenApiTestRequestData) error {<br> // extract context from provided httpReq and attach timeout<br> // Feel free to skip that step or to adjust timeout.<br> reqContext, cancel := context.WithTimeout(testData.HttpReq.Context(), 10*time.Second)<br> defer cancel()<br><br> // get new instance of router for a document for extracting our desired path&#39;s data<br> router, err := NewOpenApiRouter(testData.OpenApiDoc)<br> if err != nil {<br>  return fmt.Errorf(&quot;NewOpenApiRouter(); err = %v&quot;, err)<br> }<br><br> // find route in schema or fail<br> route, pathParams, err := router.FindRoute(testData.HttpReq)<br> if err != nil {<br>  return fmt.Errorf(&quot;router.FindRoute(); err = %v&quot;, err)<br> }<br><br> // build request validation input for validation against schema<br> requestValidationInput := &amp;openapi3filter.RequestValidationInput{<br>  Request:    testData.HttpReq, // our mocked request provided from test<br>  PathParams: pathParams, // all params for our endpoint&#39;s path<br>  Route:      route, // details route data from OpenAPI config<br>  Options:    testData.RequestValidationOptions, // all of our options we provided from test<br> }<br><br> // retrieve context from provided request object<br> // and validate our request object<br> // if you need to skip some pieces, add it into Options<br> err = openapi3filter.ValidateRequest(reqContext, requestValidationInput)<br> if err != nil {<br>  return fmt.Errorf(&quot;openapi3filter.ValidateRequest(); err = %v&quot;, err)<br> }<br><br> // create response recorder to cast response from mocked request<br> responseRecorder := httptest.NewRecorder()<br><br> // assign handler func<br> handler := http.HandlerFunc(testData.HandlerCallback)<br><br> // serve mocked endpoint for given request<br> handler.ServeHTTP(responseRecorder, testData.HttpReq)<br><br> // begin::validate response against OpenApi Schema<br><br> // make sure to validate against all returned status code<br> testData.ResponseValidationOptions.IncludeResponseStatus = true<br><br> responseValidationInput := &amp;openapi3filter.ResponseValidationInput{<br>  RequestValidationInput: requestValidationInput,<br>  Status:                 responseRecorder.Code, // check expected status code<br>  Header:                 responseRecorder.Header(), // check expected headers<br>  Options:                testData.ResponseValidationOptions, // our options for response from test<br> }<br> <br> // attach response body to response object from recorder before validation!<br> responseValidationInput.SetBodyBytes(responseRecorder.Body.Bytes())<br> err = openapi3filter.ValidateResponse(reqContext, responseValidationInput)<br> if err != nil {<br>  return fmt.Errorf(&quot;openapi3filter.ValidateResponse(); err = %v&quot;, err)<br> }<br><br> // validate expected substring is in response body<br> // we check it because example values from config are not used for validation<br> if testData.ExpectedBodySubstring != &quot;&quot; {<br>  if !strings.Contains(string(responseRecorder.Body.Bytes()), testData.ExpectedBodySubstring) {<br>   return fmt.Errorf(&quot;testData.ExpectedBodySubstring not found. Want: [%s] | Got: %s&quot;,<br>    testData.ExpectedBodySubstring, string(responseRecorder.Body.Bytes()))<br>  }<br> }<br><br> // end::validate response against OpenApi Schema<br><br> return nil<br>}</pre><p><strong>Let’s see how our OpenAPI tests helper file looks like in full:</strong></p><pre>// {root}/internal/utils/testutils/openapi.go<br>package testutils<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;net/http/httptest&quot;<br> &quot;strings&quot;<br> &quot;time&quot;<br><br> &quot;github.com/getkin/kin-openapi/openapi3&quot;<br> &quot;github.com/getkin/kin-openapi/openapi3filter&quot;<br> &quot;github.com/getkin/kin-openapi/routers&quot;<br> &quot;github.com/getkin/kin-openapi/routers/gorillamux&quot;<br> &quot;github.com/go-chi/chi/v5&quot;<br>)<br><br>// Details of the endpoint defined in OpenApi file<br>type OpenApiPathDetails struct {<br> Method        string<br> PathOperation *openapi3.Operation<br>}<br><br>// RouterPathDetails details of the path defined on Router<br>type RouterPathDetails struct {<br> Method string<br>}<br><br>// OpenApiTestRequestData struct holding all required parameters for testing endpoints<br>// including request, special options (f.ex. for excluding some checks), options for validation response,<br>// and endpoint handler callback<br>type OpenApiTestRequestData struct {<br> // HttpReq - your *http.Request. Build it in your test and deliver. You can attach context, too.<br> HttpReq *http.Request<br><br> // Document needs to be scanned before and delivered to keep flexibility<br> OpenApiDoc *openapi3.T<br><br> // Options for Request Validation for controlling of what gets tested<br> RequestValidationOptions *openapi3filter.Options<br><br> // Options for Response Validation for controlling of what gets tested<br> ResponseValidationOptions *openapi3filter.Options<br><br> // Your Handler code to mock endpoint&#39;s behaviour<br> HandlerCallback func(w http.ResponseWriter, r *http.Request)<br><br> // String that is expected to appear in response. Empty string skips check<br> ExpectedBodySubstring string<br>}<br><br>// LoadOpenApiYmlFile load OpenApi yaml/json file<br>//<br>// # Make sure to have already executed godotenv.Load before using it<br>func LoadOpenApiConfigFile() *openapi3.T {<br> loader := openapi3.NewLoader()<br><br> // I recommend updating it to absolute path with ENV vars...<br> doc, err := loader.LoadFromFile(&quot;{YOUR_ABSOLUTE_PATH_GOES_HERE}&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed load swagger spec: %v&quot;, err)<br> }<br><br> return doc<br>}<br><br>// GetOpenApiPathsData - builds a map with all routes and their details<br>//<br>// # It is loaded from config file for OpenApi<br>//<br>// If (for method) `PathOperation == nil` that means there is no route defined<br>//<br>// # Params:<br>//<br>// - openApiDoc: *openapi3.T<br>//<br>// # Returns:<br>//<br>// - map[string][]OpenApiPathDetails<br>func GetOpenApiPathsData(openApiDoc *openapi3.T) map[string][]OpenApiPathDetails {<br> openApiPaths := map[string][]OpenApiPathDetails{}<br><br> // build paths data from OpenAPI<br> for path, pathItem := range openApiDoc.Paths.Map() {<br>  openApiPaths[path] = []OpenApiPathDetails{<br>   {Method: http.MethodGet, PathOperation: pathItem.Get},<br>   {Method: http.MethodPut, PathOperation: pathItem.Put},<br>   {Method: http.MethodDelete, PathOperation: pathItem.Delete},<br>   {Method: http.MethodPost, PathOperation: pathItem.Post},<br>   {Method: http.MethodPatch, PathOperation: pathItem.Patch},<br>  }<br> }<br><br> return openApiPaths<br>}<br><br>// GetRouterPathsData - builds a map with all routes and their methods<br>//<br>// # Params:<br>//<br>// - router: *chi.Mux<br>//<br>// # Returns:<br>//<br>// - map[string][]RouterPathDetails<br>//<br>// - error<br>func GetRouterPathsData(router *chi.Mux) (map[string][]RouterPathDetails, error) {<br> routerPaths := map[string][]RouterPathDetails{}<br> err := chi.Walk(router, func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {<br>  routerPaths[route] = append(routerPaths[route], RouterPathDetails{Method: method})<br>  return nil<br> })<br><br> return routerPaths, err<br>}<br><br>func NewOpenApiRouter(openApiDoc *openapi3.T) (routers.Router, error) {<br> return gorillamux.NewRouter(openApiDoc)<br>}<br><br>// OpenApiTestRequest - perform full test of request against OpenApi Document:<br>//<br>// 1. Test request body before sending it to endpoint (possible control via testData.testData.RequestValidationOptions)<br>//<br>// 2. Mock server and serve endpoint with provided handler<br>//<br>// 3. Test received response<br>//<br>// # Options<br>//<br>// Both request and response objects take Options as parameter, so you can control behaviour of this test.<br>//<br>// # Params<br>//<br>// testData: OpenApiTestRequestData<br>//<br>// # Returns<br>//<br>// - error: in case something fails. You can use it to fail test<br>func OpenApiTestRequest(testData OpenApiTestRequestData) error {<br> // extract context from provided httpReq and attach timeout<br> reqContext, cancel := context.WithTimeout(testData.HttpReq.Context(), 10*time.Second)<br> defer cancel()<br><br> // get new instance of router for a document<br> router, err := NewOpenApiRouter(testData.OpenApiDoc)<br> if err != nil {<br>  return fmt.Errorf(&quot;NewOpenApiRouter(); err = %v&quot;, err)<br> }<br><br> // find route in schema or fail<br> route, pathParams, err := router.FindRoute(testData.HttpReq)<br> if err != nil {<br>  return fmt.Errorf(&quot;router.FindRoute(); err = %v&quot;, err)<br> }<br><br> // build request validation input for validation against schema<br> requestValidationInput := &amp;openapi3filter.RequestValidationInput{<br>  Request:    testData.HttpReq,<br>  PathParams: pathParams,<br>  Route:      route,<br>  Options:    testData.RequestValidationOptions,<br> }<br><br> // retrieve context from provided request object<br> // and validate our request object<br> // if you need to skip some pieces, add it into Options<br> err = openapi3filter.ValidateRequest(reqContext, requestValidationInput)<br> if err != nil {<br>  return fmt.Errorf(&quot;openapi3filter.ValidateRequest(); err = %v&quot;, err)<br> }<br><br> // create response recorded to cast response from mocked request<br> responseRecorder := httptest.NewRecorder()<br><br> // assign handler func<br> handler := http.HandlerFunc(testData.HandlerCallback)<br><br> // serve mocked endpoint for given request<br> handler.ServeHTTP(responseRecorder, testData.HttpReq)<br><br> // begin::validate response against OpenApi Schema<br><br> // make sure to validate against all returned status codes<br> testData.ResponseValidationOptions.IncludeResponseStatus = true<br> responseValidationInput := &amp;openapi3filter.ResponseValidationInput{<br>  RequestValidationInput: requestValidationInput,<br>  Status:                 responseRecorder.Code,<br>  Header:                 responseRecorder.Header(),<br>  Options:                testData.ResponseValidationOptions,<br> }<br> responseValidationInput.SetBodyBytes(responseRecorder.Body.Bytes())<br> err = openapi3filter.ValidateResponse(reqContext, responseValidationInput)<br> if err != nil {<br>  return fmt.Errorf(&quot;openapi3filter.ValidateResponse(); err = %v&quot;, err)<br> }<br><br> // validate expected substring is in response body<br> if testData.ExpectedBodySubstring != &quot;&quot; {<br>  if !strings.Contains(string(responseRecorder.Body.Bytes()), testData.ExpectedBodySubstring) {<br>   return fmt.Errorf(&quot;testData.ExpectedBodySubstring not found. Want: [%s] | Got: %s&quot;,<br>    testData.ExpectedBodySubstring, string(responseRecorder.Body.Bytes()))<br>  }<br> }<br><br> // end::validate response against OpenApi Schema<br><br> return nil<br>}</pre><p>If you are using sample repo, content of the file can be found <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/internal/utils/testutils/openapi.go"><strong>HERE</strong></a><strong>.</strong></p><h3>Let’s see how we can test if all our routes in Router and in OpenAPI config file are in sync</h3><p>The file we are going to analyse now can be found <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/openapi_test.go"><strong>HERE</strong></a></p><p>Please, pay attention to comments since these contain explanation what is being done.</p><pre>// {root}/openapi_test.go<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;strings&quot;<br> &quot;testing&quot;<br><br> apiRouter &quot;github.com/bluznierca1/go-chi-swagger-testing/internal/router&quot;<br> &quot;github.com/bluznierca1/go-chi-swagger-testing/internal/utils/testutils&quot;<br> &quot;github.com/getkin/kin-openapi/openapi3&quot;<br>)<br><br>var (<br> openApiDoc *openapi3.T<br>)<br><br>// Load OpenAPI file via package once (it will crash if something goes wrong)<br>func TestMain(m *testing.M) {<br> openApiDoc = testutils.LoadOpenApiConfigFile()<br> m.Run()<br>}<br><br>// TestOpenApi_CheckRegisteredRoutes tests the alignment between<br>// OpenAPI documentation and Chi router.<br>func TestOpenApi_CheckRegisteredRoutes(t *testing.T) {<br><br> // Extract paths and their methods from OpenAPI documentation<br> // it will be obtained in our own format (wrapper)<br> openApiPaths := testutils.GetOpenApiPathsData(openApiDoc)<br><br> // Initialize Chi router (our main one!) and extract its paths with methods<br> router := apiRouter.SetupRouter()<br> routerPaths, err := testutils.GetRouterPathsData(router)<br> if err != nil {<br>  t.Fatalf(&quot;testutils.GetRouterPathsData(); err = %v&quot;, err)<br> }<br><br> // Slice to collect discrepancies<br> var discrepancies []string<br><br> // Preprocess OpenAPI methods into a map<br> openApiMethodsMap := preprocessOpenApiMethods(openApiPaths)<br><br> // Preprocess Router methods into a map<br> routerMethodsMap := preprocessRouterMethods(routerPaths)<br><br> // begin::Check OpenAPI to Router<br> for path, openApiPathDetails := range openApiPaths {<br>  _, exists := routerPaths[path]<br>  if !exists {<br>   discrepancies = append(discrepancies, fmt.Sprintf(&quot;Missing path [%s] in Router&quot;, path))<br>   continue<br>  }<br><br>  for _, openApiDetail := range openApiPathDetails {<br>   if openApiDetail.PathOperation == nil {<br>    continue<br>   }<br>   if !routerMethodsMap[path][openApiDetail.Method] {<br>    discrepancies = append(discrepancies, fmt.Sprintf(&quot;Missing method [%s] for path [%s] in Router&quot;, openApiDetail.Method, path))<br>   }<br>  }<br> }<br> // end::Check OpenAPI to Router<br><br> // begin::Check Router to OpenAPI<br> for path, routerPathDetails := range routerPaths {<br>  _, exists := openApiPaths[path]<br>  if !exists {<br>   discrepancies = append(discrepancies, fmt.Sprintf(&quot;Missing path [%s] in OpenAPI file.&quot;, path))<br>   continue<br>  }<br><br>  for _, routerDetail := range routerPathDetails {<br>   if !openApiMethodsMap[path][routerDetail.Method] {<br>    discrepancies = append(discrepancies, fmt.Sprintf(&quot;Missing method [%s] for path [%s] in OpenAPI file.&quot;, routerDetail.Method, path))<br>   }<br>  }<br> }<br> // end::Check Router to OpenAPI<br><br> // Report all discrepancies <br> if len(discrepancies) &gt; 0 {<br>  t.Errorf(&quot;Route discrepancies found:\n%s&quot;, strings.Join(discrepancies, &quot;\n&quot;))<br> }<br>}<br><br>// preprocessOpenApiMethods converts OpenAPI path details into a map for easier usage<br>func preprocessOpenApiMethods(paths map[string][]testutils.OpenApiPathDetails) map[string]map[string]bool {<br> methodsMap := make(map[string]map[string]bool)<br> for path, details := range paths {<br>  if _, exists := methodsMap[path]; !exists {<br>   methodsMap[path] = make(map[string]bool)<br>  }<br>  for _, detail := range details {<br>   if detail.PathOperation != nil {<br>    methodsMap[path][detail.Method] = true<br>   }<br>  }<br> }<br> return methodsMap<br>}<br><br>// preprocessRouterMethods converts Router path details into a map for easier usage<br>func preprocessRouterMethods(paths map[string][]testutils.RouterPathDetails) map[string]map[string]bool {<br> methodsMap := make(map[string]map[string]bool)<br> for path, details := range paths {<br>  if _, exists := methodsMap[path]; !exists {<br>   methodsMap[path] = make(map[string]bool)<br>  }<br>  for _, detail := range details {<br>   methodsMap[path][detail.Method] = true<br>  }<br> }<br> return methodsMap<br>}</pre><p>Great! We got our tests checking if endpoints registered on Router are in sync with what we have in OpenAPI config file!</p><p><strong>Let’s go further!</strong></p><h3>Testing endpoints behaviour against OpenAPI defined schema</h3><p>The handler we will focus on can be accessed via GET “/api/get-record/{id}” and it will:</p><ul><li>Return 422 (Unprocessable Entity) response when our provided `{id}` is not an integer greater than 0</li><li>Return 200 (Status OK) response when provided {id} == 5</li><li>Return 404 (Not Found) response when {id} &gt; 0 &amp;&amp; {id} != 5</li><li>For each response, it will attach “Content-Type: application/json” Header and JSON body with basic data or error description.</li></ul><p>Keep in mind that this code is only for showing testing setup, and not for having beautfully refactored working app ;)</p><p>Full file with that handler can be found <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/internal/api/handler/ping_handler.go"><strong>HERE</strong></a></p><p><strong>Let’s have a look at our handler:</strong></p><pre>// {root}/internal/api/handler/ping_handler.go<br>func (p *PingHandler) GetRecord(w http.ResponseWriter, r *http.Request) {<br> var marshalledResponseBody []byte<br><br> w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br> // prepare our response when param {id} does not fit expectations<br> invalidIdResponseBody := struct {<br>  ErrorCode string `json:&quot;error_code&quot;`<br>  ErrorMsg  string `json:&quot;error_msg&quot;`<br> }{<br>  ErrorCode: &quot;err_invalid_id&quot;,<br>  ErrorMsg:  &quot;Id must be integer greater than 0.&quot;,<br> }<br><br> // validate {id} (recommended to move it into some validator helper or middleware)<br> id, err := strconv.ParseInt(chi.URLParam(r, &quot;id&quot;), 10, 0)<br> if err != nil || id &lt; 1 {<br>  // let&#39;s ignore error for sake of simplicity of example...<br>  // and just return our marshalled struct with err_invalid_id error<br>  marshalledResponseBody, _ = json.Marshal(invalidIdResponseBody)<br>  w.WriteHeader(http.StatusUnprocessableEntity)<br>  w.Write(marshalledResponseBody)<br>  return<br> }<br><br> // If provided id is 5, let&#39;s return success for our case<br> if id == 5 {<br>  // prepare basic successful response<br>  successResponseBody := struct {<br>   Id int `json:&quot;id&quot;`<br>  }{<br>   Id: 5,<br>  }<br>  // let&#39;s agree skipping error in here is allowed... ;)<br>  marshalledResponseBody, _ = json.Marshal(successResponseBody)<br>  w.WriteHeader(http.StatusOK)<br>  w.Write(marshalledResponseBody)<br>  return<br> }<br><br> // if id != 5, return not found response<br> notFoundResponseBody := struct {<br>  ErrorCode string `json:&quot;error_code&quot;`<br>  ErrorMsg  string `json:&quot;error_msg&quot;`<br> }{<br>  ErrorCode: &quot;err_not_found&quot;,<br>  ErrorMsg:  &quot;Entity not found.&quot;,<br> }<br><br> // and again error ignoring... ;)<br> marshalledResponseBody, _ = json.Marshal(notFoundResponseBody)<br><br> w.WriteHeader(http.StatusNotFound)<br> w.Write(marshalledResponseBody)<br>}</pre><p>That handler is registered on our Router as below (code is available <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/internal/router/router.go"><strong>HERE</strong></a><strong>)</strong></p><h3>So it is time to see our helpers in action!</h3><p>Whole file is available in <a href="https://github.com/bluznierca1/go-chi-swagger-testing/blob/main/internal/api/handler/ping_handler_test.go"><strong>HERE</strong></a></p><p>Here we can see and analyse Test that will allow us to check all scenarios for the endpoint as well as confronting it with OpenAPI config file of ours:</p><pre>func TestPingHandler_GetRecord(t *testing.T) {<br>// Use that URL because of my openapi.yml file in which I defined servers.url<br>// it must match exactly<br> urlBase := &quot;https://to-be-defined.whoknows/api/get-record/&quot;<br><br> // build array of structs containing our testing scenarios (table driven testing)<br> testCases := []struct {<br>  name                  string // name of our test to be used as 1st param for t.Run)<br>  body                  string // payload for the request<br>  expectedStatusCode    int // status code we expect from response<br>  expectedBodySubString string // string we expect in response body. It can be full response or just substring<br>  id                    string // id that we provide for our endpoint&#39;s {id} param<br> }{<br>  {<br>   name:                  &quot;invalid_id_param&quot;,<br>   body:                  &quot;&quot;,<br>   expectedStatusCode:    http.StatusUnprocessableEntity,<br>   expectedBodySubString: &quot;err_invalid_id&quot;,<br>   id:                    &quot;-1&quot;,<br>  },<br>  {<br>   name:                  &quot;not_found&quot;,<br>   body:                  &quot;&quot;,<br>   expectedStatusCode:    http.StatusNotFound,<br>   expectedBodySubString: &quot;err_not_found&quot;,<br>   id:                    &quot;1&quot;,<br>  },<br>  {<br>   name:                  &quot;record_found&quot;,<br>   body:                  &quot;&quot;,<br>   expectedStatusCode:    http.StatusOK,<br>   expectedBodySubString: &quot;5&quot;,<br>   id:                    &quot;5&quot;,<br>  },<br> }<br><br> // run test scenarios<br> for _, tc := range testCases {<br>  t.Run(tc.name, func(t *testing.T) {<br><br>   // build used url by attaching value for {id} in the path<br>   url := urlBase + tc.id<br><br>   // build the request which will be later used for validating against OpenAPI scchema<br>   // attach Method, URL and Payload<br>   httpReq, err := http.NewRequest(http.MethodGet, url, strings.NewReader(tc.body))<br>   if err != nil {<br>    // if something went wrong, don&#39;t bother going further.<br>    t.Fatalf(&quot;http.NewRequest(); err = %v&quot;, err)<br>   }<br><br>   // Create a new chi.RouteContext and set the URL parameter<br>   // that is because in testing env our Router is not initialised,<br>   // so chi.URLParam(r, &quot;id&quot;) (which we use for extracting {id} from path) would always return empty string<br>   rctx := chi.NewRouteContext()<br>   rctx.URLParams.Add(&quot;id&quot;, tc.id)<br><br>   // Attach the chi.RouteContext to the request&#39;s context<br>   // to make sure handler<br>   ctx := context.WithValue(httpReq.Context(), chi.RouteCtxKey, rctx)<br>   httpReq = httpReq.WithContext(ctx)<br><br>   // skip auth check on our schema as route not protected<br>   // You will need to provide auth data otherwise and you can delete that code<br>   requestOptions := &amp;openapi3filter.Options{<br>    AuthenticationFunc: openapi3filter.NoopAuthenticationFunc,<br>   }<br><br>   responseOptions := &amp;openapi3filter.Options{}<br><br>   // Let&#39;s put our testutils openapi helper to use<br>   testData := testutils.OpenApiTestRequestData{<br>    HttpReq:                   httpReq, // request with endpoint, method and payload<br>    OpenApiDoc:                openApiDoc, // parsed OpenAPI config file<br>    RequestValidationOptions:  requestOptions, // all options for external package for our Request validation<br>    ResponseValidationOptions: responseOptions, // all options for external package for our Responsevalidation<br>    HandlerCallback: func(w http.ResponseWriter, r *http.Request) {<br>     // CRUCIAL PART - trigger handler&#39;s method for handling endpoint.<br>     // it will receive our defined Request and request listener<br>     pingHandler := &amp;PingHandler{}<br>     pingHandler.GetRecord(w, r)<br>    },<br>    ExpectedBodySubstring: tc.expectedBodySubString,<br>   }<br><br>   // Trigger testing helper validating provided request, triggering callback and validating response<br>   // in case of error being returned, we mark test as failed.<br>   err = testutils.OpenApiTestRequest(testData)<br>   if err != nil {<br>    t.Fatalf(&quot;testutils.OpenApiTestRequest(); err = %v&quot;, err)<br>   }<br>  })<br> }<br>}</pre><h3>Wrapping it up</h3><p>I hope you have checked comments on the code examples I provided because these were containing explanation of taken steps as well as types of data we are using.</p><p><strong>The core file for allowing us to testing logic is the helper we have containing methods helping us with:</strong></p><ol><li>Loading and parsing OpenAPI config file</li><li>Extracting routes from both Router and OpenAPI config file</li><li>Executing mocked request, executing callback, recording request and validating request payload as well as request responses against OpenAPI schema.</li></ol><p>Using these helpers for testing endpoints’ behaviour against OpenAPI schema made my testing easier, more centralised and easier to maintain.</p><p>I hope you can find that setup helpful for you.</p><p>In case you see the ways to optimise it, please share it in the comment or create GitHub Issue (Pull Requests with suggestions are more than welcome!)</p><p>GitHub repo: <a href="https://github.com/bluznierca1/go-chi-swagger-testing">https://github.com/bluznierca1/go-chi-swagger-testing</a></p><p><strong>PS Package which made this setup possible can be found here: </strong><br><a href="http://github.com/getkin/kin-openapi">https://github.com/getkin/kin-openapi</a></p><p>Greetings,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17a2e7c069c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Soft Deletes in Golang with ent: A Guide to Mixins and Interceptors]]></title>
            <link>https://medium.com/@bluznierca1/implementing-soft-deletes-in-golang-with-ent-a-guide-to-mixins-and-interceptors-399c327d3cfe?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/399c327d3cfe</guid>
            <category><![CDATA[soft-delete]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ent]]></category>
            <category><![CDATA[mixin]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Fri, 17 May 2024 06:24:28 GMT</pubDate>
            <atom:updated>2024-05-17T06:24:28.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cover image showing a Golang gopher with a ‘Soft Delete’ shield in front of a database icon." src="https://cdn-images-1.medium.com/max/1024/1*8zeThnAtWZPZ2E_3VGE6fg.jpeg" /></figure><p>Hi!</p><p>As everyone working with data stored in databases knows, permanently deleting records isn’t always the best idea. We might lose valuable information and make data recovery impossible (of course, there are backups, but it’s better to be proactive than reactive). To help us retain records while keeping them “unavailable,” we can use a soft delete implementation.</p><p>Recently, I was asked to help implement this feature in a Golang Web API project using <a href="https://entgo.io/"><strong>entgo.io</strong></a> for database interactions. Even though there is an example on the official website on how to implement an interceptor for this purpose (<a href="https://entgo.io/docs/interceptors/#soft-delete"><strong>check it out</strong></a>), for some reason it was still quite problematic.</p><p>Therefore, I am writing this article to clarify the topic and hopefully make it easier for others to implement soft deletes or other custom features via Mixins and interceptors in their own projects.</p><h3>Prerequisites</h3><p>Since you’re reading this article, you should already have your project set up with <a href="https://entgo.io/"><strong>entgo.io</strong></a> and connected to a database. We&#39;ll skip unnecessary introductions to concepts since official documentation does explain them clearly. I will just mention these and provide links for further reading.</p><p>Please, get familiar with below concepts for better understanding of what we are using and why.</p><p>Note that the best way to implement the soft delete feature in <a href="https://entgo.io/"><strong>entgo.io</strong></a> is by using an interceptor. You can read about interceptors <a href="https://entgo.io/docs/interceptors/"><strong>here</strong></a>. An interceptor can be added to an entity via a Mixin, which you can learn more about <a href="https://entgo.io/docs/schema-mixin"><strong>here</strong></a>.<br>We are also going to be dealing with hooks which you can read more about <a href="https://entgo.io/docs/hooks/"><strong>here</strong></a></p><p>Using a Mixin with an interceptor allows for easy reuse across multiple entities, enabling centralised control of the implemented feature (soft delete in our case) for all entities that use it.</p><h3>Implementation</h3><p>Let’s take a User entity as an example — the approach will be the same for other entities. In my case, all entities are defined in the &lt;myproject&gt;/internal/ent/schema folder. Based on that, our package name for the file will be schema.</p><p>Below is the initial draft of a User entity before implementing the interceptor. Notice the deleted_at field, which at this stage results in a hard delete of records (via client.DeleteOne method). That is what we want to change.</p><pre>package schema<br><br>import (<br> &quot;time&quot;<br><br> &quot;entgo.io/ent&quot;<br> &quot;entgo.io/ent/schema/field&quot;<br>)<br><br>type User struct {<br> ent.Schema<br>}<br><br>func (User) Fields() []ent.Field {<br> return []ent.Field{<br>  field.Int64(&quot;id&quot;),<br>  field.String(&quot;name&quot;),<br>  field.String(&quot;username&quot;).Unique(),<br>  field.String(&quot;email&quot;).Unique(),<br>  field.String(&quot;password&quot;),<br>  field.Enum(&quot;role&quot;).Values(&quot;admin&quot;, &quot;user&quot;, &quot;medium_reader&quot;),<br>  field.Time(&quot;created_at&quot;).Immutable().Default(time.Now),<br>  field.Time(&quot;updated_at&quot;).Default(time.Now).UpdateDefault(time.Now),<br>  // deleted_at field soon will be redundant in here<br>  field.Time(&quot;deleted_at&quot;).Optional().Nillable(),<br> }<br>}</pre><p>So, as we can see, all is standard here.</p><p>If we wanted to implement Soft Delete functionality right now (since <a href="https://entgo.io/"><strong>entgo.io</strong></a><strong> </strong>does not have it built-in), we could just perform UPDATE of that field on DELETE request but that is not why we are going through that article.</p><h3>Import Cycle Not Allowed</h3><p>As in official documentation <a href="https://entgo.io/docs/interceptors/#interceptors-registration"><strong>here</strong></a><strong> </strong>, when using interceptors in our schema, we need to make sure we do register everything correctly or we will end up with import cycle not allowed error.</p><p>The whole instruction of how to do it is in the Hooks Registration section (the same procedure case) which you can find <a href="https://entgo.io/docs/hooks#hooks-registration"><strong>here</strong></a><strong> </strong>.</p><p>That is what took a while for me to make things work, so I am going to describe the process on a more clear way (according to me…). Although that now I know how things work, official documentation makes more sense…</p><p><strong>This is description for when you are about to create your Mixin.<br>If you already have one but it is not working yet, comment out your code and follow described steps. That should work, too</strong></p><p>Let’s go through how I approached registering my Mixin with interceptor:</p><h4>1. Update ent/generate.go file</h4><p>The content of my &lt;myproject&gt;/internal/ent/generate.go file:</p><pre>package ent<br><br>//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature intercept,schema/snapshot ./schema</pre><p>It mostly differs from original one because we add — feature intercept,schema/snapshot part which is required to make interceptors work.<br>That will create a new file: ent/intercept/intercept.go for you on generation which will be used in a Mixin in this case.</p><p>After you follow step 2, do not get confused — ./schema path from ent/generate.go <strong>stays the same</strong>. It needs to point to your entities, not custom types (mixing, interceptors, custom structs etc.).</p><h4>2. Create schematype dir in your schema directory</h4><p>Inside of my schema dir (now it is useful to know name), I created a new directory called schematype where I have placed mixin_soft_delete.go .<br>Its content is quite the same as in official documentation (<a href="https://entgo.io/docs/interceptors/#soft-delete"><strong>here</strong></a>) with the difference of name for the column: deleted_at</p><p><strong>IMPORTANT TO NOTICE </strong><br>If you change column name like me, you need to be aware you also need to change method name in newly generated interface.<br>SetDeletedAt(time.Time) instead of SetDeleteTime(time.Time)</p><pre>package schematype<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> gen &quot;&lt;myproject&gt;/internal/ent&quot; // my whole folder with ent files<br> &quot;&lt;myproject&gt;/internal/ent/hook&quot; // auto generated<br> &quot;&lt;myproject&gt;/internal/ent/intercept&quot; // auto generate after updating the ent/generate.go<br> &quot;time&quot;<br><br> // all below are just imported ent files<br> &quot;entgo.io/ent&quot;<br> &quot;entgo.io/ent/dialect/sql&quot;<br> &quot;entgo.io/ent/schema/field&quot;<br> &quot;entgo.io/ent/schema/mixin&quot;<br>)<br><br>// SoftDeleteMixin implements the soft delete pattern for schemas.<br>type SoftDeleteMixin struct {<br> mixin.Schema<br>}<br><br>// Fields of the SoftDeleteMixin.<br>// Once you declare &quot;deleted_at&quot; in here, you MUST DELETE IT from the entity that will use that Mixin<br>func (SoftDeleteMixin) Fields() []ent.Field {<br> return []ent.Field{<br>  field.Time(&quot;deleted_at&quot;).<br>   Optional(),<br> }<br>}<br><br>type softDeleteKey struct{}<br><br>// SkipSoftDelete returns a new context that skips the soft-delete interceptor/mutators.<br>func SkipSoftDelete(parent context.Context) context.Context {<br> return context.WithValue(parent, softDeleteKey{}, true)<br>}<br><br>// Interceptors of the SoftDeleteMixin.<br>func (d SoftDeleteMixin) Interceptors() []ent.Interceptor {<br> return []ent.Interceptor{<br>  intercept.TraverseFunc(func(ctx context.Context, q intercept.Query) error {<br>   // Skip soft-delete, means include soft-deleted entities.<br>   if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {<br>    return nil<br>   }<br>   d.P(q)<br>   return nil<br>  }),<br> }<br>}<br><br>// Hooks of the SoftDeleteMixin.<br>func (d SoftDeleteMixin) Hooks() []ent.Hook {<br> return []ent.Hook{<br>  hook.On(<br>   func(next ent.Mutator) ent.Mutator {<br>    return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {<br>     // Skip soft-delete, means delete the entity permanently.<br>     if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {<br>      return next.Mutate(ctx, m)<br>     }<br><br>     mx, ok := m.(interface {<br>      SetOp(ent.Op)<br>      Client() *gen.Client<br>      SetDeletedAt(time.Time) // That is the line that needs to be updated if you change column name to be deleted_at<br>      WhereP(...func(*sql.Selector))<br>     })<br>     if !ok {<br>      return nil, fmt.Errorf(&quot;unexpected mutation type %T %+v&quot;, m, m)<br>     }<br>     d.P(mx)<br>     mx.SetOp(ent.OpUpdate)<br>     mx.SetDeletedAt(time.Now())<br>     return mx.Client().Mutate(ctx, m)<br>    })<br>   },<br>   ent.OpDeleteOne|ent.OpDelete,<br>  ),<br> }<br>}<br><br>// P adds a storage-level predicate to the queries and mutations.<br>func (d SoftDeleteMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) {<br> w.WhereP(<br>  sql.FieldIsNull(d.Fields()[0].Descriptor().Name),<br> )<br>}</pre><h4>3. import _ “&lt;project&gt;/ent/runtime”</h4><p>Include import _ “&lt;project&gt;/ent/runtime” in the main package file OR just in the package where you initialise ent.Client — all depends on preference. I personally placed it in package I setup my ent.Client</p><h4>4. First run of “go generate ./…”</h4><p>Of course, if you have other generators that you don’t want to trigger, you can run sth like go generate ./internal/ent/ to trigger generation only for <br>ent.</p><p>If ent generator is the only one you got, in the root folder of your project just execute go generate ./...</p><p><strong>IMPORTANT TO NOTICE<br></strong>go generate ./internal/ent/ command is for my setup because I have generate.go file for ent in that folder.<br>If, for some reason, you moved that generate.go file (for ent ) somewhere else, update your path accordingly.</p><p>That generation will update the generated ent package to point to the new package. For example, schema.T becomes schematype.T</p><h4>5. Use the Mixin in your entities</h4><p>As you noticed, before running go generate ./internal/ent/ we have NOT used our new Mixin. That is because it would trigger the import cycle not allowed error which we are trying to avoid and at that stage, generate command would result in error and exit.</p><p>As example to use our new Mixin on our entity, here is the code with explanation in comments, so pay attention to them:</p><pre>package schema<br><br>import (<br> // here we import our new schematype package with mixins!<br> // At this stage your IDE WILL COMPLAIN about &quot;import cycle not allowed&quot; but discard it because we are going to fix it now<br> &quot;&lt;myproject&gt;/internal/ent/schema/schematype&quot;<br> &quot;time&quot;<br><br> &quot;entgo.io/ent&quot;<br> &quot;entgo.io/ent/schema/field&quot;<br>)<br><br>type User struct {<br> ent.Schema<br>}<br><br>func (User) Fields() []ent.Field {<br> return []ent.Field{<br>  field.Int64(&quot;id&quot;),<br>  field.String(&quot;name&quot;),<br>  field.String(&quot;username&quot;).Unique(),<br>  field.String(&quot;email&quot;).Unique(),<br>  field.String(&quot;password&quot;),<br>  field.Enum(&quot;role&quot;).Values(&quot;admin&quot;, &quot;user&quot;, &quot;medium_reader&quot;),<br>  field.Time(&quot;created_at&quot;).Immutable().Default(time.Now),<br>  field.Time(&quot;updated_at&quot;).Default(time.Now).UpdateDefault(time.Now),<br>  // deleted_at field is now DELETED since our Mixing does implement it<br>  // if you attach it here, it will trigger error<br> }<br>}<br><br>// Mixin - here we are attaching our schematype.SoftDeleteMixin to our User entity<br>// You can add more Mixins if you need. That is basically it!<br>func (User) Mixin() []ent.Mixin {<br> return []ent.Mixin{<br>  schematype.SoftDeleteMixin{},<br> }<br>}</pre><p>We added 2 things in here:</p><ol><li>import &lt;myproject&gt;/internal/ent/schema/schematype — if your IDE does complain about “import cycle not allowed” — DO NOT WORRY, it is expected at that level, we are going to fix it in next step.</li><li>Registered our SoftDeleteMixin on our User entity (Mixin method). You can register more mixins if needed by adding them to array.</li></ol><h4>6. Let’s fix that “import cycle not allowed” error</h4><p>As mentioned, importing our package &lt;myproject&gt;/internal/ent/schema/schematype will be, at this moment, tagged as wrong.</p><p>All you need to do right now is just repeat step 4 from our list —<strong> generate files again</strong>.</p><p>Thanks to magic that is caused by auto generated “&lt;project&gt;/ent/runtime” package, the import cycle not allowed should be now fixed!</p><h4>7. Keep coding!</h4><h3>Let’s wrap it up</h3><p>Implementing soft deletes in an ent-based Golang project can streamline your data management and ensure that important records are not permanently lost. By leveraging Mixins and interceptors, you can centralize and reuse the soft delete functionality across multiple entities.</p><p>Soft Delete Mixing is just an example of how to implement any kind of custom re-usable feature you need. Here I just focused on simplifying the explanation of the process of making it work.</p><p>Remember to create one file per Mixin to keep your project organised and maintainable. This approach not only keeps your codebase clean but also makes it easier to manage and extend your custom features used on entities in the future.</p><p>Greetings,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=399c327d3cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PHP Namespaces: Organising Your Code]]></title>
            <link>https://medium.com/@bluznierca1/understanding-php-namespaces-organising-your-code-ba2590c5e529?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba2590c5e529</guid>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[composer]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 15:24:27 GMT</pubDate>
            <atom:updated>2023-11-07T15:28:13.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNkqB2C8c_Ys1ZIuzyPsxQ.jpeg" /></figure><p>Code clarity should not just be a goal, it should be a standard and to help with that, we are about to explore PHP namespaces.</p><p>Namespaces are like the silent librarians of PHP, always ensuring that everything is in its right place (at least for the dev who works on a project… ;)). If you’re looking to keep your code clean and conflict-free, understanding namespaces is key.</p><p>Let’s explore how this powerful feature can bring order to your code.</p><h3>What are PHP Namespaces?</h3><h4>Technical definition</h4><p>Namespaces in PHP are designated areas that allow you to group related code elements like classes, interfaces, functions, constants, enums, traits etc. <br>It’s a way to encapsulate elements to ensure that names are unique in a given context.<br>PHP namespaces are comparable to the directories on a computer — without them, there would be no way to distinguish between items with the same name.</p><h4>Real-Life Example</h4><p>Consider a library as an analogy for namespaces in PHP. In a library, books are organised into sections based on genres like fiction, non-fiction, science, history etc. <br>Inside each section, books are further categorised by authors and titles. You could find a book titled “The Great Adventure” in both the fiction and non-fiction sections, but because they are categorised under different genres, there’s no confusion about which book you’re referring to when you specify its section.</p><p>In this scenario, each genre acts like a namespace, and the books represent different classes or functions within that namespace. Just as the library’s organisation system prevents confusion over book titles, PHP namespaces prevent confusion over class names or function names, allowing developers to use the same name in different “sections” of their code without any mix-ups.</p><h3>The Syntax of Namespaces</h3><p>To utilise namespaces in PHP, you need to understand the syntax that defines and references them. It’s the rulebook for creating and calling upon these unique identifiers in your code. Here’s how it works:</p><h4>Declaring a Namespace</h4><p>At its simplest, a namespace is declared at the beginning of a PHP file using the namespace keyword followed by the desired name of the namespace. It must be the first statement in the file, before any other code, except for a declare statement:</p><pre>// Let&#39;s say this is MyProject.php file in the root of the project<br>&lt;?php<br><br>namespace MyProject;<br><br>class User {}</pre><p>In the above example, the User class is part of the MyProject namespace. It’s as if we’ve filed this class under a folder named MyProject.</p><h4>Referencing a Namespace</h4><p>When you want to use a class or function from a namespace, you reference it by its full name, which includes the namespace (there is “simpler” way, but let’s explore all options):</p><pre>&lt;?php<br><br>require_once(&quot;app/User.php&quot;); // we will get rid of that later... ;)<br><br>// Let&#39;s say this is index.php file in the root of the project<br>$user = new \MyProject\User;</pre><p><strong>Using Sub-namespaces</strong></p><pre>// Let&#39;s say this is file: app/Database/Connection.php<br>&lt;?php<br>namespace MyProject\Database;<br><br>class Connection {}</pre><p>Here, the Connection class is placed within a sub-namespace Database, under the main MyProject namespace.<br><strong>In PHP, usually, namespace should match the folder structure the file is placed in.</strong></p><h4>Importing Namespaces</h4><p>As mentioned earlier, there is “simpler” way of using Namespaces.<br>To avoid writing out long namespace names every time, PHP offers the use keyword to import a namespace:</p><pre>// Let&#39;s say this is index.php file in the root of the project<br>&lt;?php<br><br>require_once(&quot;app/Database/Connection.php&quot;); // we will get rid of it later ;)<br><br>use MyProject\Database\Connection;<br><br>// No need to write full namespace<br>$conn = new \MyProject\Database\Connection;<br><br>// Now, thanks to &quot;use&quot; statement, we can do as below:<br>$conn = new Connection;</pre><p>By importing the Connection class with the use statement, we can reference it more succinctly.</p><h4>Using Aliases</h4><p>Sometimes class names get quite lengthy. For our sake, there is an option to use alias for the class:</p><pre>&lt;?php<br><br>require_once(&quot;app/Services/SomeDataProviderAuthService.php&quot;) //stay patient...<br><br>use MyProject\Services\SomeDataProviderAuthService as SomeDPAuth;<br><br>// If we didn&#39;t use alias, we would have to do:<br>$conn = new SomeDataProviderAuthService;<br><br>// but thanks to aliases, we can use:<br>$conn = new SomeDPAuth;</pre><p>That is especially useful when (for some unknown reason) our project contains 2 classes with the same name (under different namespaces) and we need to use both of these in the code.</p><pre>&lt;?php<br><br>require_once(&quot;app/FirstIntegration/Database/Connection.php&quot;);<br>require_once(&quot;app/SecondIntegration/Database/Connection.php&quot;); // patience... ;)<br><br>// If we left it as below, we would get error:<br>// &quot;Cannot use &#39;Connection&#39; because the name is already in use&quot;<br>use MyProject\FirstIntegration\Database\Connection;<br>use MyProject\SecondIntegration\Database\Connection;<br><br>// That is why aliases come handy:<br>use MyProject\FirstIntegration\Database\Connection as FIDbConn;<br>use MyProject\SecondIntegration\Database\Connection as SIDbConn;<br><br>$firstDbConn = new FIDbConn();<br>$secondDbDonn = new SIDbConn();</pre><h3>Autoloading with Namespaces</h3><h4>Efficiency in Code Management</h4><p>In PHP, the concept of “autoloading” allows for the automatic loading of class files whenever they’re needed, eliminating the need for manual require or include statements for every class (thankfully!). Namespaces enhance this process, giving a structured, predictable path to the class files.</p><p>No more “require()”, “require_once()”, “include()”, “include_once()” for unless needed explicitly!</p><p>Let’s see how to achieve it.</p><h4>PSR-4 Autoloading Standard</h4><p>The PHP community has adopted a collection of standards known as PSR (PHP Standard Recommendations), which outline best practices for coding styles, interfaces, and autoloading.</p><p>PSR-4 is specifically tailored for autoloading and pairs seamlessly with namespaces. It dictates that each namespace should correspond to a directory structure. <br>This means that if you have a class MyProject\Database\Connection, it should be located in a file that follows the path MyProject/Database/Connection.php, relative to a designated base directory.<br>Good IDEs will show warnings if that is not followed.</p><h4>Composer and Autoloading</h4><p>Composer, a dependency manager for PHP, provides a powerful and flexible autoloader out of the box. <br>By default, it uses the PSR-4 standard for autoloading classes. To leverage Composer’s autoloader, you define the mapping between your namespaces and directories in the composer.json file.</p><p>Let’s have a look at example of composer.json from Laravel (only “autoload” part:</p><pre>    &quot;autoload&quot;: {<br>        &quot;psr-4&quot;: {<br>            &quot;App\\&quot;: &quot;app/&quot;,<br>            &quot;Database\\Factories\\&quot;: &quot;database/factories/&quot;,<br>            &quot;Database\\Seeders\\&quot;: &quot;database/seeders/&quot;<br>        }<br>    }</pre><p>With this configuration, Composer will automatically load any class within the App namespace from the src/ directory, Database\Factories namespace from the database/factories/ directory and DatabaseSeeders namespace from database/seeders/ directory.</p><h4>Putting It All Together</h4><p>Once you’ve defined your autoloading rules in composer.json, you run composer dump-autoload to generate the vendor/autoload.php file.</p><p>Including this file in your project (require &#39;vendor/autoload.php&#39;;) usually in base file (most often in root of the project index.php file) sets up autoloading for your entire application.</p><p>Now, when you instantiate a class, Composer&#39;s autoloader will automatically include the necessary file based on the namespace and class name, as long as it adheres to the PSR-4 structure.</p><p>This system ensures that your classes are loaded on-demand and that the class paths are easily managed, making the codebase easier to understand and navigate.</p><h3>Namespaces in action</h3><p>Let’s explore a few different examples of accessing methods/classes on different ways via namespaces.</p><h4>Accessing Static Methods</h4><p>Implementation in the Math class:</p><pre>&lt;?php<br><br>// File: app/Utilities/Math.php<br><br>namespace App\Utilities;<br><br>class Math {<br>    public static function calculateSum($a, $b) {<br>        return $a + $b;<br>    }<br>}</pre><p>Using the Math class:</p><pre>&lt;?php<br>// File: index.php or any other PHP file that uses Math.php<br><br>require &#39;path/to/app/Utilities/Math.php&#39;; // Let&#39;s assume we didn&#39;t implement autoloading<br><br>use App\Utilities\Math;<br><br>$result = Math::calculateSum(10, 20);<br>echo $result; // Output: 30</pre><h4>Group Use Declarations</h4><p>Let’s say we have 2 different classes in the same folder, so most of their namespace will be the same.</p><p>First file:</p><pre>&lt;?php<br>// File: app/Service/ServiceOne.php<br><br>namespace App\Service;<br><br>class ServiceOne {<br>    // Implementation of ServiceOne<br>}</pre><p>Second file:</p><pre>// File: app/Service/ServiceTwo.php<br><br>namespace App\Service;<br><br>class ServiceTwo {<br>    // Implementation of ServiceTwo<br>}</pre><p>And now we want to use both in the index.php file:</p><pre>&lt;?php<br>// File: index.php or any other PHP file that uses the services<br><br>// let&#39;s require these...<br>require &#39;path/to/app/Service/ServiceOne.php&#39;;<br>require &#39;path/to/app/Service/ServiceTwo.php&#39;;<br><br>// Originally we could do that:<br>use App\Service\ServiceOne;<br>use App\Service\ServiceTwo;<br><br>// But here comes grouping:<br>use App\Service\{ServiceOne, ServiceTwo};<br><br>// Yes, we can also do aliasing!:<br>use App\Service\{ServiceOne as First, ServiceTwo as Second};</pre><h4>Calling Namespaced Functions</h4><p>We are not tied only to classes, we can also implement methods under the namespaces.</p><p>Declaration of a namespaced function:</p><pre>&lt;?php<br>// File: app/Helpers/array_helpers.php<br><br>namespace App\Helpers;<br><br>function array_flatten(array $array) {<br>    $result = [];<br>    array_walk_recursive($array, function($a) use (&amp;$result) {<br>        $result[] = $a;<br>    });<br>    return $result;<br>}</pre><p>Using the namespaced function:</p><pre>&lt;?php<br>// File: index.php<br><br>require &#39;path/to/app/Helpers/array_helpers.php&#39;;<br><br>use function App\Helpers\array_flatten;<br><br>$array = [ [1, 2], [3, 4] ];<br>$flat = array_flatten($array);<br>print_r($flat); // Output: Array ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 [3] =&gt; 4 )</pre><p><strong>Using Namespaced Constants</strong></p><p>Another example when it is not only about classes.</p><p>Definition of a namespaced constant:</p><pre>&lt;?php<br>// File: app/Settings/constants.php<br><br>namespace App\Settings;<br><br>const MAX_USERS = 100;</pre><p>Using the namespaced constant:</p><pre>&lt;?php<br>// File: index.php<br><br>require &#39;path/to/app/Settings/constants.php&#39;;<br><br>use const App\Settings\MAX_USERS;<br><br>$userCount = 50;<br><br>echo $userCount &gt; MAX_USERS ?<br>  &quot;User limit exceeded&quot; :<br>  &quot;User count within limit&quot;;</pre><p>Namespaces in PHP serve as a robust mechanism for categorising and organising various components of our codebase. <br>As demonstrated, their use extends beyond just classes to encompass constants, functions, traits, interfaces, enums, and other standalone language constructs. This flexibility enables developers to manage code in a modular fashion, preventing name conflicts and fostering a clean, maintainable architecture.</p><h3>Let’s sum it up</h3><p>Embracing namespaces in PHP is a decisive step towards writing clearer, more organised code.<br>They solve the age-old problem of name collisions and pave the way for larger, more complex applications.</p><p>Now, knowing how to declare, import, and use namespaces, you are now better equipped to keep your codebase tidy and conflict-free.</p><p>Also, now you got no excuse to not use that concept powering each project ;)</p><p>Namespaces are not just a feature; they are an essential practice in the modern PHP developer’s workflow.</p><p>Have you found this article helpful and want to keep me awake for writing more? <br>Here is your chance to get me a coffee: <a href="https://www.buymeacoffee.com/grzegorzlaT">https://www.buymeacoffee.com/grzegorzlaT</a></p><p>Greetings,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba2590c5e529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interfaces and Types in TypeScript: Let’s check them]]></title>
            <link>https://medium.com/@bluznierca1/interfaces-and-types-in-typescript-lets-check-them-4ee751561a23?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee751561a23</guid>
            <category><![CDATA[typescript-types]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 12:01:20 GMT</pubDate>
            <atom:updated>2023-10-17T12:01:20.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QgzbPpk9z6nIMoITu_MZA.jpeg" /></figure><p>Programming in TypeScript provides us with a powerful toolset to develop applications with robust static type-checking. <br>Two key components in TypeScript’s type system are <strong>“Interfaces”</strong> and <strong>“Types.”</strong> <br>On the surface, they might appear synonymous, but as we delve deeper into their nuances, we will be able to see their differences both in theory and practice.</p><p><em>Note: This article focuses solely on the use of Interfaces and Types in TypeScript, which have unique characteristics distinct from other languages.</em></p><h3><strong>Interface — let’s have a look</strong></h3><p>Imagine you’re planning to build a house. Every house needs a foundation, walls, a roof, and windows. While the materials used for the walls or the design of the roof might vary, these fundamental parts are necessary for the house to be complete and functional.</p><p>In programming, when we create a blueprint (or a plan) for an object, we call it an “Interface.” The object is like the house, and the foundation, walls, roof, and windows are like its properties or methods. The interface tells us what parts (or properties and methods) an object needs to have, and it might even specify what type they should be. However, just like in house-building where we have flexibility in choosing materials or designs, in programming, the exact details or behaviors of those properties and methods can vary, as long as they fit the blueprint.</p><p>Let’s dive into 3 different examples of how we can use Interfaces in TS.<br>Please, pay attention to comments added to the code.</p><p><strong>1. Treating an Object as an Interface without explicit using of “implements”</strong></p><pre>// our Interface<br>interface Vehicle {<br>    wheels: number;<br>    color: string;<br>}<br><br>// Function expecting param of type Vehicle<br>function describeVehicle(v: Vehicle) {<br>    console.log(`This is a ${v.color} vehicle with ${v.wheels} wheels.`);<br>}<br><br>// bike fulfills contract for Vehicle - it has all required props<br>// Could be also functions<br>const bike = {<br>    wheels: 2,<br>    color: &quot;red&quot;<br>};<br><br>describeVehicle(bike); // This will work just fine because object fulfills contract provided by Interface<br><br>// We can use &quot;as&quot; BUT be careful (next example).<br>// Using &quot;as&quot; can also help us in case function&#39;s parameter supports f.ex. Vehicle | {ANOTHER_INTERFACE}<br>describeVehicle(bike as Vehicle);<br><br>// We are missing &quot;color&quot; property, so contract is not fulfilled<br>const car = { <br>  wheels: 4<br>}<br><br>describeVehicle(car); // this will throw compile error since it is missing &quot;wheels&quot;<br><br>// BUT...<br>// Using &quot;as&quot; explicitly would supress compile error but we would get runtime error since<br>// describeVehicle() function does not check if props exist on provided object.<br>// So, be careful with TS perks<br>describeVehicle(car as Vehicle);</pre><p>In TypeScript, the principle of structural typing means that objects are assessed by their shape rather than just formal type annotations. So, even if you don’t explicitly say that an object implements an interface, as long as the object has properties that fit the shape of that interface, TypeScript understands and treats it accordingly. This is why our bike object is recognised as a Vehicle even without an explicit declaration.</p><p>The as keyword provides a way to directly specify types, but it comes with a caveat. As demonstrated with the car object, misuse can bypass compile-time checks, risking runtime errors. This showcases TypeScript&#39;s adaptability, but it&#39;s also a call for developers to use its tools carefully.</p><p><strong>2. Class implements Interface which requires parameters and functions</strong></p><pre>// our Interface<br>interface Building {<br>    material: string;<br>    floors: any; // &quot;any&quot; means you can have actually ANY type as value.<br>    describe(): string;<br>}<br><br>// Class fulfilling the contract for Interface<br>class Skyscraper implements Building {<br>    material: string;<br>    floors: any;<br><br>    constructor(material: string, floors: any) {<br>        this.material = material;<br>        this.floors = floors;<br>    }<br><br>    // We use ${this.floors} in here as a (string | number) although it has type of &quot;any&quot;.<br>    // In here, all good as long as we get (string | number) but we got problem if we get f.ex. some Object...?<br>    describe(): string {<br>        return `A ${this.material} building with ${this.floors} floors.`;<br>    }<br>}<br><br>const tower = new Skyscraper(&quot;glass&quot;, &quot;many&quot;);<br>console.log(tower.describe());  // This will log: &quot;A glass building with many floors.&quot;<br><br><br>// With below class, we get compile error since describe() method is not implemented on the class.<br>class WrongBuilding implements Building {<br>    material: string;<br>    floors: any;<br><br>    constructor(material: string, floors: any) {<br>        this.material = material;<br>        this.floors = floors;<br>    }<br>}</pre><p>The Skyscraper class implements Building interface, complete with properties and a constructor for initialisation. It also provides the describe method that combines these into a descriptive sentence.</p><p>However, the flexibility of the floors property being of type any can lead to potential pitfalls. In the describe method, we seamlessly incorporate floors into a string using template literals. While this works for strings or numbers, more complex types might result in unexpected outcomes. Always be as strict about types as possible.</p><p><strong>3. Interface with String Index Signature</strong></p><pre>interface Dictionary {<br>    [key: string]: string;<br>    definition: string;  // Explicit property<br>}<br><br>const englishDictionary: Dictionary = {<br>    &quot;apple&quot;: &quot;A fruit.&quot;,<br>    &quot;car&quot;: &quot;A vehicle.&quot;,<br>    definition: &quot;A statement of the exact meaning of a word.&quot;<br>};<br><br>console.log(englishDictionary[&quot;apple&quot;]);  // This will log: &quot;A fruit.&quot;</pre><p>The Dictionary interface illustrates TypeScript&#39;s dynamic property handling with its index signature [key: string]: string, while also enforcing an explicit definition property. The englishDictionary object adheres to this by combining both dynamic (&quot;apple&quot; and &quot;car&quot;) and explicit properties. Accessing values, like englishDictionary[&quot;apple&quot;], underscores the dictionary-like behaviour in TypeScript.</p><h4>Can we somehow extend Interfaces?</h4><p>Sure we can. That can be achieved on 3 different ways and some of them can lead to unexpected issues if used not carefully.</p><ol><li><strong>Interface Extension<br></strong>By using the extends keyword, an interface can inherit properties and methods from another interface, building a chain of progressively specialised interfaces.</li></ol><pre>// Our Interface<br>interface BaseVehicle {<br>    wheels: number;<br>}<br><br>// Here you can extend chosen Interface.<br>// interface Car will inherit EVERYTHING from BaseVehicle<br>interface Car extends BaseVehicle {<br>    doors: number;<br>}<br><br>// ${sedan} does fulfill contract for merged Interfaces, so it is fine<br>const sedan: Car = {<br>    wheels: 4,<br>    doors: 4<br>};<br><br>// ${house} fulfill contract only for Car but since Car extends BaseVehicle,<br>// we are missing &quot;wheels&quot; property and we&#39;ll get compile error.<br>const house: Car = {<br>    doors: 5<br>}</pre><p><strong>2. Interface Merging<br></strong> If you declare an interface with the same name more than once, TypeScript <strong>automatically merges their members into a single interface</strong>. This can be especially useful for incremental definitions, but <strong>caution is advised to avoid unintended overlaps.</strong></p><pre>interface Car {<br>    wheels: number;<br>}<br><br>// we just redefine Car interface and all props will get merged automatically!<br>interface Car {<br>    doors: number;<br>}<br><br>// Since Interfaces are merged automatically, ${sedan} needs to implement<br>// both properties to fulfill promise<br>const sedan: Car = {<br>    wheels: 4,<br>    doors: 4<br>};<br><br>// At this stage ${wrongObject} is NOT fulfilling Interface&#39;s contract<br>// It will result in compile error<br>const wrongObject: Car = {<br>    wheels: 4<br>}</pre><p>3. <strong>Intersection Types<br></strong>Beyond just interfaces, TypeScript provides a way to combine multiple types using the &amp; operator. This approach can mix different type structures, from interfaces to type aliases, into one composite type ( we will get to Types soon).</p><pre>interface Engine {<br>    power: number;<br>    type: string;<br>}<br><br>interface Vehicle {<br>    wheels: number;<br>}<br><br>type EngineVehicle = Engine &amp; Vehicle;<br><br>// At this stage, we got 3 props to fulfill contract with interface<br>const sportsCar: EngineVehicle = {<br>    power: 450,<br>    type: &#39;V8&#39;,<br>    wheels: 4<br>};</pre><p>Interfaces in TypeScript play a pivotal role in establishing blueprints for structured data and behaviour. They allow us to define the shape of data, enforce contracts within our code, and provide a consistent base for development. Through our exploration:</p><ul><li>We’ve seen how interfaces can be imagined as building plans, where the expectations (like materials and components) are laid out for objects or classes to fulfil.</li><li>We’ve delved into practical application, illustrating how objects or classes can implicitly or explicitly adhere to the structure and contract set by an interface.</li><li>Finally, we’ve looked at the versatility of interfaces in TypeScript, learning about their extensibility through extension, merging, and intersection types.</li></ul><p>As we transition to our next section, we’ll dive deeper into <strong>Types</strong>, exploring their unique characteristics and how they differ and sometimes overlap with <strong>Interfaces</strong>.</p><h3>Types — let’s explore it</h3><p>If interfaces in TypeScript are like blueprints, ensuring that structures follow a particular shape or pattern, then Types are like the raw materials with which you craft those structures. They provide the flexibility and precision to mold the data structures in ways that interfaces might not, offering a broader range of possibilities.</p><h4>What are Types in TypeScript?</h4><p>In TypeScript, Types help us categorise data into specific (well…) types like numbers, strings, or booleans. Yet, TypeScript goes beyond these basic types, providing mechanisms to define complex data structures and relationships between them.</p><p>Consider a scenario where you need to describe a user and their address:</p><pre>// Very simple type with basic data types.<br>// Pay attention - here we use &quot;=&quot; to define the Type<br>type Address = {<br>    street: string;<br>    city: string;<br>    postalCode: number;<br>};<br><br>// More complex example where we use composition -<br>// we embed one Type into another<br>type User = {<br>    name: string;<br>    age: number;<br>    roles: string[];  // An array of roles represented by array of strings<br>    address: Address;  // Using our Address type<br>    isActive?: boolean;  // An optional property (undefined | boolean)<br>};</pre><p>One notable distinction between types and interfaces is the use of the = sign when defining types. This assignment operator is used because, under the hood, a type alias is akin to setting up an alias or a new name for a particular shape or structure, much like assigning a value to a variable.</p><p>While this example may look similar to an interface, type aliases can capture more complex structures and patterns. They can represent function types, union types, and much more. As we proceed, we’ll delve deeper into the versatility of type aliases and how they often intersect with, and diverge from, interfaces.</p><h4>How can we use Types?</h4><ol><li><strong>Implicit Type Checking with Types<br></strong>Just like with Interfaces, TypeScript performs implicit type checking. If an object’s structure matches the defined type, you don’t necessarily need to explicitly specify the type.</li></ol><pre>type Car = {<br>    wheels: number;<br>};<br><br>function getWheels(car: Car) {<br>    return car.wheels;<br>}<br><br>// TypeScript knows {wheels: 4} fits the &quot;Car&quot; type without explicitly stating it.<br>getWheels({wheels: 4});</pre><p><strong>2. Utilising Types with Generics<br></strong>Generics introduce the idea of type variables, making it possible to handle multiple types.</p><pre>type Container&lt;T&gt; = {<br>    value: T;<br>};<br><br>const numberContainer: Container&lt;number&gt; = { value: 42 };<br>const stringContainer: Container&lt;string&gt; = { value: &quot;Hello, World!&quot; };</pre><p>3. <strong>Using Type Aliases for Complex Structures</strong><br>Types can represent intricate and detailed structures, making them suitable for modeling real-world data.</p><pre>type Address = {<br>    street: string;<br>    city: string;<br>    postalCode: string;<br>};<br><br>type User = {<br>    name: string;<br>    age: number;<br>    address: Address; // we embed one type into another<br>};<br><br>const user: User = {<br>    name: &#39;Alice&#39;,<br>    age: 28,<br>    address: { // Now the &quot;address&quot; has to match Address Type<br>        street: &#39;123 Main St&#39;,<br>        city: &#39;Wonderland&#39;,<br>        postalCode: &#39;12345&#39;<br>    }<br>};</pre><p>4. <strong>Defining Function Types within Types<br></strong>In TypeScript, you can also clearly define the signature of functions within your types. This ensures that any function adhering to this type will have the correct parameters and return type.</p><pre>type capitalizeStringFunctionType = {<br>    (stringToCapitalize: string, numberOfLettersToCapitalize: number): string;<br>};<br><br>type camelCaseFunctionType = {<br>    (stringValue: string): string;<br>};<br><br>export type useStringHelperType = {<br>    capitalizeString: capitalizeStringFunctionType;<br>    camelCase: camelCaseFunctionType;<br>};<br><br>export function useStringHelper(): useStringHelperType {<br><br>    function capitalizeString (<br>        stringToCapitalize: string,<br>        numberOfLettersToCapitalize = 0 as number<br>    ): string {<br>        // logic goes here...<br>        return &quot;&quot;;<br>    }<br><br>    function camelCase(stringValue: string): string { <br>        // logic goes here...<br>        return &quot;&quot;;<br>    }<br><br>    return {<br>        capitalizeString,<br>        camelCase<br>    }<br><br>}</pre><p>In this example, the types capitalizeStringFunctionType and camelCaseFunctionType define the signature for two different functions. They&#39;re then bundled together in the useStringHelperType type. This ensures that the useStringHelper function returns an object with two functions adhering to their respective types. By doing this, you&#39;re creating a contract that ensures consistency in the behavior of functions, making the code safer and more predictable.</p><p>5. <strong>Using Types with Classes<br></strong>One might wonder if Interfaces are the only way to type-check class structures in TypeScript. The answer is... NO! <br>Just like interfaces, TypeScript allows classes to adopt specific shapes using Types.</p><pre>// Our Type with <br>type AnimalType = {<br>    species: string;<br>    sound: any; // we can also define here &quot;any&quot; type but again, be careful!<br>    makeSound: () =&gt; string; // functions can also be &quot;contracted&quot;<br>};<br><br>class Dog implements AnimalType { // The same syntax like for Interfaces!<br>    species = &#39;Canine&#39;;<br>    sound = &#39;Woof&#39;;<br><br>    makeSound() {<br>        return this.sound;<br>    }<br>}<br><br>const myDog = new Dog();<br>console.log(myDog.makeSound());  // Logs: &quot;Woof&quot;</pre><p>In this section, we’ve just scratched the surface of the potential of TypeScript’s types. Through our exploration, we delved into scenarios where types help in defining data structures, guiding function behaviour, and even creating contracts for more complex functionalities.</p><p>In the next section, we will look into possibility of extending Types but not only!</p><h4>Extending Types and more</h4><p>In TypeScript, types can be combined, modified, and extended using various utility types provided by the language.</p><p>Let’s explore our options:</p><ol><li><strong>Intersection (&amp;) — </strong>Combine multiple types into one.</li></ol><pre>type Name = {<br>    name: string;<br>};<br><br>type Age = {<br>    age: number;<br>};<br><br>// Let&#39;s &quot;extend&quot; our Type (similar to extending Interfaces)<br>type Person = Name &amp; Age; // Person is now merge ot Name &amp; Age.</pre><p>2. <strong>Union (|) —</strong> Represents a value that could be one of several types.</p><pre>type ID = string | number;<br>const idString: ID = &quot;myUniqueId&quot;; <br>const idNumber: ID = 123;<br>const idBool: ID = true; // we get error since type does not fit.<br><br>// The same type but fixed values<br>type Action = &quot;edit&quot; | &quot;update&quot;;<br>const actionEdit: Action = &quot;edit&quot;;<br>const actionSave: Action = &quot;save&quot;; // &quot;save&quot; does not fit given option, so we will get compile error.</pre><p>3. <strong>And More: Special Utility Types<br></strong>TypeScript offers numerous utility types to mold and transform types:</p><ul><li><strong>Pick</strong>: Choose specific fields from a type.</li></ul><pre>type User = {<br>    id: number;<br>    name: string;<br>    password: string;<br>};<br><br>// So, now &quot;password&quot; is not &quot;contracted&quot; anymore!<br>type SafeUser = Pick&lt;User, &#39;id&#39; | &#39;name&#39;&gt;;</pre><ul><li><strong>Omit</strong>: Exclude certain fields from a type.</li></ul><pre>type User = {<br>    id: number;<br>    name: string;<br>    password: string;<br>};<br><br>// So, now &quot;password&quot; is not &quot;contracted&quot; anymore!<br>type SafeUserAgain = Omit&lt;User, &#39;password&#39;&gt;;</pre><ul><li><strong>Partial</strong>: Make all properties optional.</li></ul><pre>type User = {<br>    id: number;<br>    name: string;<br>    password: string;<br>};<br><br>// So, now ALL parameters are optional!<br>type PartialUser = Partial&lt;User&gt;;</pre><ul><li><strong>Required</strong>: Make all properties required.</li></ul><pre>type User = {<br>    id: number;<br>    name: string;<br>    password: string;<br>};<br><br>// So, now ALL parameters from User are optional on PartialUser!<br>type PartialUser = Partial&lt;User&gt;;<br><br>// And now RequiredUser does Required ALL params from PartialUser<br>type RequiredUser = Required&lt;PartialUser&gt;;</pre><ul><li><strong>Readonly</strong>: Make properties readonly.</li></ul><pre>type User = {<br>    id: number;<br>    name: string;<br>    password: string;<br>};<br><br>// You cannot change values on ImmutableUser from now<br>type ImmutableUser = Readonly&lt;User&gt;;<br><br>const user: ImmutableUser = {<br>    id: 1,<br>    name: &quot;Grzegorz&quot;,<br>    password: &quot;password&quot; // you know... ;)<br>}<br><br>user.name = &quot;John&quot;; // Error: Cannot assign to &#39;name&#39; because it is a read-only property.</pre><ul><li><strong>Record</strong>: Create a type with set keys and the same type of values.</li></ul><pre>// You define your type in here but all props will be of type &quot;string&quot;<br>type ThreeStrings = Record&lt;&#39;prop1&#39; | &#39;prop2&#39; | &#39;prop3&#39;, string&gt;;<br><br>const threeStringObj: ThreeStrings = {<br>    prop1: &quot;value1&quot;,<br>    prop2: &quot;value2&quot;,<br>    prop3: &quot;value3&quot;<br>}</pre><ul><li><strong>NonNullable</strong>: Excludes null and undefined from a type.</li></ul><pre>type Names = NonNullable&lt;string | null | undefined&gt;;<br><br>const name: Names = &quot;Grzegorz&quot;; // is just fine<br><br>const anonymous: Names = undefined; // Error: Type &#39;undefined&#39; is not assignable to type &#39;string&#39;.</pre><ul><li><strong>ReturnType</strong>: Gets the return type of a function.</li></ul><pre>type ResultType = ReturnType&lt;() =&gt; number&gt;;<br><br>function workingOne( callback: ResultType ): number {<br>    return callback;<br>}<br><br>// Error: Type &#39;number&#39; is not assignable to type &#39;string&#39;.<br>// because out ResultType will return number and our fn declares string and return type<br>function brokenOne( callback: ResultType ): string {<br>    return callback;<br>}</pre><ul><li><strong>InstanceType</strong>: Gets the instance type of a constructor function type.</li></ul><pre>class MyClass {<br>    x = 0;<br>    y = 0;<br>}<br><br>type MyClassInstance = InstanceType&lt;typeof MyClass&gt;;<br><br>const myClass: MyClassInstance = {<br>    x: 1,<br>    y: 2<br>}<br><br>// This won&#39;t work because it does not fulfill expected contract (x, y)<br>const brokenClass: MyClassInstance = {<br>    name: &quot;Grzegorz&quot;<br>}</pre><p>These utilities can greatly enhance the expressiveness and safety of your type definitions. By leveraging them, you can craft complex and comprehensive types that will fit project’s requirements, ensuring better type safety and clearer code (hopefully…).</p><h3>Let’s sum it up</h3><p>We have covered what are Interfaces and Types, how to use them, how these can be extended and we dived into more advanced techniques for the Types.</p><p>Looking at these 2, they seem quite alike because at the beginning they are but real differences can be seen when working on more complex project where it might be helpful to “omit” or “pick” some of properties from another Type instead of defining new Interfaces from beginning.</p><p>I am not going to point out where I would see fit of using one over another since, as usual, it depends…</p><p>I hope you find that article helpful and it will make your journey with TypeScript a bit clearer in that matter.</p><p>Best regards,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee751561a23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Legacy Labyrinths: Navigating and Patching a Web App Lost to Time]]></title>
            <link>https://medium.com/@bluznierca1/legacy-labyrinths-navigating-and-patching-a-web-app-lost-to-time-77a91e2b3a3e?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a91e2b3a3e</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[legacy]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 14:59:54 GMT</pubDate>
            <atom:updated>2023-10-01T14:59:54.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7ZPVD4sECSZN-uVpTRnSA.jpeg" /></figure><h3>A side gig.</h3><p>A few small updates to make old application better for users. That’s all it was supposed to be.<br>An innocent dive into a legacy Angular-Laravel project. <br>But in a twist fit for a digital detective novel, <strong>15 minutes in, and boom — admin access</strong>. Who knew old code could be so… welcoming?</p><p><strong>And that was just the beginning.</strong> <br>As I waded deeper into this codebase, I encountered mysteries like dependencies that had ghosted us and an “npm install” command that was more like a cruel joke. <br>And just for some added drama? <br>My grand debut, the initial deployment, was a <strong>masterclass in how not to make an entrance.</strong></p><p>Ready for a tour through this maze? Strap in!</p><h3>How did I get into the project?</h3><p>Friend’s friend needed a developer to make a few changes to his web application. The tasks seemed straightforward: purge records marked as ‘deleted’, cleanse the database of certain entries that, due to their sensitive nature, had no business being retained, make a few tweaks in front-end, so things are more intuitive for users.</p><p>Just some basic jobs, or so it seemed…</p><h4>Obtaining Admin Credentials from the app…</h4><p>Before the official meeting with the app owner, I wanted to check the application out to have some basics. Just to familiarise myself with the lay of the land. Given that I’d soon be diving deep into its code, it seemed like a logical first step.</p><p>However, as I idly wandered through the app, I stumbled upon a peculiar quirk. Out of curiosity, I decided to see how the app’s API would handle a request to a non-existent URL. Imagine my surprise when, instead of the standard ‘404 — Not Found’ or even an error message, I was greeted with logs. <strong>And not just any logs — these were requests logs, including authentication logs.</strong></p><p>Like finding an oasis in a desert, there it was amidst the data drought: <strong>the admin’s password, in clear and bold plain text</strong>.</p><p>That was an ace in my sleeve before the meeting with app owner.</p><h4>The meeting</h4><p>As expected — the owner wanted to know how much time it will take for required changes but knowing that nobody has touched application for 4 years (no updates at all!), providing reasonable estimate was quite a challenge.</p><p>Then the time for my ace came — I asked him to watch my screen where I just logged into his app as an admin.<br>Right away it became obvious this is critical issue that needs to become top priority.</p><p>Did it help me to land the gig? I do want to believe that. At least I was proud of myself.</p><h3>Setting Up the Time Machine — Development</h3><p>The code was stored in BitBucket, so it was quite easy to get it on my machine (but we will get back to Git piece in this article…)</p><p><strong>Docker?</strong> Yeah, forget it…<br><strong>Documentation?</strong> Docu… what?<br><strong>Tests? </strong>Users will test it!</p><p>The project was done in the spirit of micro-services where API was one project and Front-End (service for users) was another. There were more projects but these did not need changes.</p><h4><strong>Let’s have a look at Laravel’s project dependencies</strong></h4><pre>{<br>      &quot;require&quot;: {<br>        &quot;php&quot;: &quot;&gt;=5.5.9&quot;,<br>        &quot;laravel/framework&quot;: &quot;5.2.*&quot;,<br>        &quot;barryvdh/laravel-cors&quot;: &quot;^0.8.0&quot;,<br>        &quot;tymon/jwt-auth&quot;: &quot;^0.5.9&quot;,<br>        &quot;guzzlehttp/guzzle&quot;: &quot;^6.2&quot;,<br>        &quot;barryvdh/laravel-debugbar&quot;: &quot;^2.2&quot;,<br>        &quot;doctrine/dbal&quot;: &quot;^2.5&quot;,<br>        &quot;dflydev/apache-mime-types&quot;: &quot;^1.0&quot;,<br>        &quot;itbz/fpdf&quot;: &quot;^1.7&quot;,<br>        &quot;intervention/imagecache&quot;: &quot;^2.3&quot;,<br>        &quot;opentok/opentok&quot;: &quot;^2.4&quot;,<br>        &quot;predis/predis&quot;: &quot;^1.1&quot;,<br>        &quot;dimsav/laravel-translatable&quot;: &quot;6.*&quot;,<br>        &quot;eluceo/ical&quot;: &quot;0.11.*&quot;,<br>        &quot;ramsey/uuid&quot;: &quot;^3.8&quot;<br>    },<br>    &quot;require-dev&quot;: {<br>        &quot;fzaninotto/faker&quot;: &quot;~1.4&quot;,<br>        &quot;mockery/mockery&quot;: &quot;0.9.*&quot;,<br>        &quot;phpunit/phpunit&quot;: &quot;~4.0&quot;,<br>        &quot;symfony/css-selector&quot;: &quot;2.8.*|3.0.*&quot;,<br>        &quot;symfony/dom-crawler&quot;: &quot;2.8.*|3.0.*&quot;,<br>        &quot;laracasts/generators&quot;: &quot;^1.1&quot;,<br>        &quot;barryvdh/laravel-ide-helper&quot;: &quot;^2.1&quot;<br>    }<br>}</pre><p><strong>PHP Version:<br></strong>Our starting point was PHP &gt;=5.5.9. At the moment, there is available <strong>PHP</strong> <strong>8.2 version</strong>…</p><p>I am very glad changing PHP version on Mac is as easy as executing:</p><pre>brew unlink php@8.2<br>brew link php@5.6</pre><p><strong>Laravel version:</strong><br>5.2 is in use. Currently, there is Laravel 10 available.<br>Just to say… Updating Laravel’s version is not just a numbers game.</p><p>To avoid going through each library, I will mention that some of them are not maintained anymore but luckily, all are still available, so that app worked just fine after switching PHP version.</p><p>Can’t say I had as much luck with Front-End Angular project…</p><h4>Front-End setup</h4><pre>{<br>    &quot;dependencies&quot;: {<br>    &quot;@angular/common&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/compiler&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/core&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/forms&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/http&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/platform-browser&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/platform-browser-dynamic&quot;: &quot;2.4.9&quot;,<br>    &quot;@angular/router&quot;: &quot;3.4.9&quot;,<br>    &quot;@ngx-translate/core&quot;: &quot;6.0.0&quot;,<br>    &quot;@ngx-translate/http-loader&quot;: &quot;0.0.3&quot;,<br>    &quot;bootstrap-sass&quot;: &quot;3.3.7&quot;,<br>    &quot;core-js&quot;: &quot;2.4.1&quot;,<br>    &quot;intl&quot;: &quot;1.2.5&quot;,<br>    &quot;moment&quot;: &quot;2.17.1&quot;,<br>    &quot;moment-timezone&quot;: &quot;0.5.11&quot;,<br>    &quot;ng2-charts&quot;: &quot;^1.6.0&quot;,<br>    &quot;ng2-file-upload&quot;: &quot;1.2.0&quot;,<br>    &quot;ng2-scrollspy&quot;: &quot;0.3.9&quot;,<br>    &quot;ng2-toastr&quot;: &quot;1.5.1&quot;,<br>    &quot;ng2-ui-auth&quot;: &quot;6.1.6&quot;,<br>    &quot;ngx-bootstrap&quot;: &quot;^1.8.1&quot;,<br>    &quot;primeng&quot;: &quot;2.0.1&quot;,<br>    &quot;primeui&quot;: &quot;4.1.15&quot;,<br>    &quot;rxjs&quot;: &quot;5.2.0&quot;,<br>    &quot;zone.js&quot;: &quot;0.7.7&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;node-sass&quot;: &quot;3.13.1&quot;,<br>    &quot;@angular/cli&quot;: &quot;1.0.0-rc.1&quot;,<br>    &quot;@angular/compiler-cli&quot;: &quot;2.4.9&quot;,<br>    &quot;@types/jasmine&quot;: &quot;2.5.38&quot;,<br>    &quot;@types/moment-timezone&quot;: &quot;0.2.34&quot;,<br>    &quot;@types/node&quot;: &quot;6.0.64&quot;,<br>    &quot;codelyzer&quot;: &quot;2.0.1&quot;,<br>    &quot;jasmine-core&quot;: &quot;2.5.2&quot;,<br>    &quot;jasmine-spec-reporter&quot;: &quot;3.2.0&quot;,<br>    &quot;karma&quot;: &quot;1.4.1&quot;,<br>    &quot;karma-chrome-launcher&quot;: &quot;2.0.0&quot;,<br>    &quot;karma-cli&quot;: &quot;1.0.1&quot;,<br>    &quot;karma-coverage-istanbul-reporter&quot;: &quot;0.2.3&quot;,<br>    &quot;karma-jasmine&quot;: &quot;1.1.0&quot;,<br>    &quot;karma-jasmine-html-reporter&quot;: &quot;0.2.2&quot;,<br>    &quot;protractor&quot;: &quot;5.1.1&quot;,<br>    &quot;ts-node&quot;: &quot;2.0.0&quot;,<br>    &quot;tslint&quot;: &quot;4.4.2&quot;,<br>    &quot;typescript&quot;: &quot;2.0.10&quot;<br>  }<br>}</pre><p><strong>Angular version<br></strong>In the app, version 2.4.9 is used.<br>Currently, there is available Angular 16.<br>Yes, there was a tear on my face…</p><p><strong>Old Dev Environment:</strong> <br>The project is using Angular CLI version 1.0.0-rc.1, which is an old release candidate version. That just could not work out of the box.</p><p><strong>Deprecated Packages:<br></strong>Packages like primeui are no longer maintained or have newer alternatives now. Continuing to use deprecated packages can be problematic because they might have unresolved bugs or security issues.</p><p><strong>Non-existing Packages:<br></strong>Some of the packages or/and their dependencies are not even available anymore, which makes installing them impossible.</p><p>Long story short — npm install command did not work as expected and the fun started.</p><h4><strong>Dependencies battle</strong></h4><p>Modern node versions wouldn’t install the project, leading me down the rabbit hole of nvm to switch to Node 6.10.0.</p><p><strong>But the missing dependencies remained a significant barrier.</strong></p><p>Just when surrender seemed imminent, a flash of inspiration struck: I could download the entire node_modules directory from the live server. And so, with a bit of ingenuity, the dev environment was resurrected on my machine.</p><h4><strong>Node version</strong></h4><p>After obtaining (thank you, FileZilla) all node_modules files manually from server, there was time to run development. That really tested my patience.</p><p>On my local machine, I currently have installed Node version of <strong>20.1.0 </strong>and that clearly was a no-go for that project which I learned after executing:</p><pre>ng serve</pre><p>Fortunately, nvm library has saved the situation because it allows to switch between Node version just like that:</p><pre>nvm install 6.10.0 &amp;&amp; nvm use 6.10.0</pre><p>I had to keep downgrading version of Node.js to find out which one would work. Didn’t expect to go that far (6.10.0) but I am glad it worked out after all!</p><h3>Let’s get back to exposed plain-text password issue</h3><p>As I mentioned, that problem became top priority, so I focused on it right away.<br>My first suspect (and bingo!) was that the app was still in the “developer” mode, so all debug information was exposed.</p><p>So we just have to update .env file, right?</p><p>Right, but first, let me get access to live server. Oh dear…</p><p>My knowledge about servers is not great and here it was challenged.</p><h4><strong>Accessing live server</strong></h4><p>The web application resided on a Digital Ocean Droplet. Once I had access to it, I also gained console privileges, allowing me to add my SSH key for seamless future connections.</p><p>I began by generating a new SSH key on my local machine. Then, I uploaded the public portion of this key to the ~/.ssh directory on the live server. I appended this key to the authorized_keys file and diligently set the correct permissions.</p><p>With everything seemingly in place, I tried connecting from my terminal.</p><p><strong>It failed.</strong></p><p>Admittedly, my server configuration knowledge is foundational rather than expert, so this posed a challenge.</p><p>A few hours of investigation later, I found the culprit in the /etc/ssh/sshd_config file, specifically under the AllowUsers directive:</p><p>AllowUsers NOT_ME_USER</p><p>My username was (for a good reason) absent.</p><p>After adding my username, adjusting file permissions, and restarting the SSH service, victory was mine: I was in!</p><p>This entire ordeal was a roller-coaster of emotions. One moment, I contemplated launching my laptop out the window but then, I felt triumphant, having conquered the server challenge.</p><h3>Diving into Development</h3><p>When it came to make code updates, fortunately, there were no surprises.<br>Of course, code was written by someone else and, of course, I would write it much better (hehe…) but it was good one for that PHP version.</p><p>Based on that, I am not going to bore you, so let’s jump into deployment because that one had surprises awaiting for me.</p><h3>Deployment — <strong>masterclass in how not to make an entrance</strong></h3><p>The moment of truth had arrived. The grin plastered on my face was so persistent that my teeth threatened to go dry from overexposure. All the changes were done and pushed to the remote repo, and all felt good. Because after solving so many problems, I thought I reached the limit of unpleasant surprises.</p><p>The app owner and I had agreed to deploy during off-peak hours — a window when user traffic was at its lowest. This would buy us some time should any unexpected issues arise. And trust me, my innate humility served me well here.</p><p>Always trust your gut, especially when it hints that overconfidence might just be your Achilles’ heel.</p><h4>‘git pull’</h4><p>The project was stored on BitBucket, meaning it was connected to Git. I managed to clone it to my machine, so I expected to execute <br>git pull command on the server and re-build Front-End project.</p><p>I have copied directory with whole live app into another one to be able to just re-link it in case something goes wrong.<br>Because, let me tell you, me and Angular just got to know each other and I did not know what surprises that old spirit of his might have for me.</p><p>So, I executed git status to check if there are some local changes and…</p><p><strong>git is not installed </strong>popped out.</p><p>And my exposed teeth just got wet from the tears dropping from my eyes.</p><h4><strong>Well, no ‘git pull’</strong></h4><p>Seems the project wasn’t the only thing gathering digital dust. The server, too, was stuck in a time warp, with outdated software.</p><p>The thought of installing Git and setting up the remote felt like tempting fate. So, I did the next best thing — manual deployment.</p><p>Time-consuming? Yes.<br>Good idea? Hell, no.<br>The best thing to do considering that these updates are last ones for next few years and app cannot be down? Yes.</p><p>But with all the changes already in place, all I had left was the project rebuild.</p><h4>Re-building project after applying changes</h4><p>I executed the build command: <br>ng build --environment live <br>To my relief, it was a success!</p><p>Excited, I launched the browser, keyed in the project’s URL, and…</p><p><strong>It was down. Of course it was.</strong></p><h4><strong>Panic mode</strong></h4><p>Instead of immediately reverting to the original version (by renaming folders), I chose to investigate the differences between the current active folder and the original one. Given the low traffic at that time, it seemed like a calculated risk.</p><p>My starting point was the dist folder, where Angular apps place their built files. I made two crucial discoveries:</p><ol><li>The URL (base href) in the index.html file was absent in the newly created file. I rectified this by using the --base-href={some.url} flag during the build process.</li><li>The .htaccess file was missing in the dist folder. Fortunately, I had the working project&#39;s copy and simply copied it over.</li></ol><p>Then, there was time for a big test of application. I opened the browser, refreshed the broken page and…</p><p><strong>It worked!</strong></p><p>I have tested all changes and these were just fine. After so many encountered problems on the way, it was a great feeling to know that code changes and manual deployment worked just fine.</p><h4>The rest of changes</h4><p>As mentioned at the beginning, on the list of required changes were the ones which had to take place in database.<br>Nothing interesting happened, so let’s just skip that part.</p><h3>Beside the changes</h3><p>Given the absence of documentation, much of my interaction with the app involved a manual discovery process. To ease any future navigation — or for any other developer fortunate (or unfortunate, depending on one’s perspective) enough to delve into this project — I’ve taken the initiative to update the README.md file.<br>This now includes instructions on setting up the development environment and the deployment process.</p><p>It’s a small step, but one that can save hours of frustration: let’s always strive to make life a tad simpler for our future selves and colleagues.</p><p>While updating the project was not the primary goal of this assignment, it’s worth noting the circumstances I operated under. The primary focus was on achieving the bare minimum due to budget considerations. Fully updating such a sizeable project would be a substantial endeavor, both in terms of time and resources.</p><h3>Let’s wrap it up</h3><p>In this article, we navigate the adventure of reviving an older web application. The journey is sprinkled with unexpected challenges, from setting up a dated development environment to tackling server mysteries, and finally, the drama of deployment surprises.</p><p>It’s a tale of persistence, the highs and lows of problem-solving, and the sweet reward of success.</p><p>Beyond the story, this experience underlines the vital importance of regular maintenance for any digital project. Let it be a reminder: keeping software updated is not merely about embracing the latest features but ensuring its long-term viability.</p><p>Regular security checks are crucial to protect both users and data especially when there is sensitive data stored.</p><p>Regarding documentation — or rather its lack — I don’t blame anyone for not writing it because I am not a fan of doing it, too.<br>Keeping dependencies updated or at least mentioning project’s caveats in README.md file can save others a lot of time, though.</p><p>This gig was tough and tested my patience, but it also taught me a lot. It’s these kinds of challenges that push us to learn and grow. Sticking to what we know is comfortable, but diving into the unknown is how we truly expand our horizons.</p><p>Greetings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a91e2b3a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Factory Pattern in PHP 8.2]]></title>
            <link>https://medium.com/@bluznierca1/exploring-the-factory-pattern-in-php-8-2-d75f2de6f22e?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75f2de6f22e</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 09:53:40 GMT</pubDate>
            <atom:updated>2023-11-07T15:28:57.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3E7d306E2Z0UidN35LvhvA.jpeg" /></figure><p>Software development is a delicate balance of problem-solving, and programming languages equip us with a variety of tools to craft effective solutions. Among these tools are ‘design patterns’ — tried-and-true solutions to common challenges we encounter. One standout pattern is the <strong>Factory Pattern</strong>, renowned for its ability to simplify and streamline object creation.</p><p>In this article, we’ll explore the Factory Pattern within the context of PHP 8.2. With the latest enhancements in PHP, we can leverage features like Enums and the match syntax, both of which breathe fresh life into the implementation of this pattern.</p><p>First we will look into traditional and simple implementation and next we will dive into a bit more advanced example to see how we can make things more complicated… Ekhm… I mean more solid and testable and repeatable and all these good things! ;)</p><p>By the article’s conclusion, you’ll not only appreciate the versatility of the Factory Pattern but also witness its practical application. Armed with this knowledge, you’ll be poised to integrate it into your own code.</p><h3>A Brief Recap of the Factory Pattern</h3><p><strong>Technical Definition:</strong> The Factory Pattern is a creational design pattern that provides an interface for creating instances of classes, with its subclasses deciding which class to instantiate. Instead of calling a class’s constructor directly, a factory method is used to create the object, abstracting the instantiation process and promoting a loose coupling between classes.</p><p>Yeah… Let’s try to get it with some day-to-day example.</p><p>Imagine you’re in a toy store, and you want a toy. Instead of making the toy yourself from scratch (which would be complicated…), you go to a special counter (let’s call it the “Toy Factory Counter”). You just tell the person behind the counter what toy you want, and they’ll give it to you. You don’t need to know how the toy is made or where it comes from; the “Toy Factory Counter” takes care of that for you.</p><p>In this scenario:</p><ul><li>The “Toy Factory Counter” is like our Factory in programming.</li><li>The act of you asking for a toy is like a piece of code asking for an object.</li><li>The person behind the counter deciding which toy to give you (maybe a doll, a robot, or a car) is like the Factory Pattern deciding which object to create based on the request.</li></ul><p>Just as the toy store simplifies the process of getting a toy, the Factory Pattern simplifies the process of creating objects in our code.</p><h3>Factory Pattern: Traditional Implementation</h3><p>Let’s continue with our toy analogy. <br>At our “Toy Factory Counter”, there’s a method (or a way) for the person behind the counter to give us toys based on our choice: a doll, a robot, or a car. If we ask for a doll, the toy factory knows it should give us a doll, and so forth. This decision-making process, simplified, is the essence of the Factory Pattern.</p><h4><strong>Implementation:</strong></h4><p>Let’s define our classes:</p><pre>class Doll {<br>    public function getDescription() {<br>        return &quot;This is a doll.&quot;;<br>    }<br>}<br><br>class Robot {<br>    public function getDescription() {<br>        return &quot;This is a robot.&quot;;<br>    }<br>}<br><br>class Car {<br>    public function getDescription() {<br>        return &quot;This is a car.&quot;;<br>    }<br>}</pre><p>Now, we’ll create our toy factory:</p><pre>class ToyFactory {<br>    public function getToy($toyType) {<br>        switch ($toyType) {<br>            case &quot;doll&quot;:<br>                return new Doll();<br>            case &quot;robot&quot;:<br>                return new Robot();<br>            case &quot;car&quot;:<br>                return new Car();<br>            default:<br>                throw new Exception(&quot;Invalid toy type&quot;);<br>        }<br>    }<br>}</pre><p>Using the factory is simple:</p><pre>$factory = new ToyFactory();<br><br>$doll = $factory-&gt;getToy(&quot;doll&quot;);<br>echo $doll-&gt;getDescription(); // Outputs: This is a doll.</pre><p>In this traditional implementation:</p><ul><li>We have a ToyFactory class that decides which toy object to create based on the toyType provided.</li><li>Instead of creating new toy objects directly using the new keyword everywhere in our code, we use the factory. This centralizes the object creation process and makes our code more organized and manageable.</li></ul><p>In the next section, we’ll see how PHP 8.2’s Enums,match syntax and Interfaces can enhance this basic structure.</p><h3><strong>A bit more advanced example of Factory Pattern implementation</strong></h3><p><strong>Heads-up:</strong> code is from Laravel 10, so some of the functions might be coming from that framework but that should not affect overall explanation.<br>Beside, Classes and Interfaces are bundled into one ‘file’ just for simplicity.<br>Please, read comments in the code as it contains further explanation of some of the code.</p><p>Also, example comes from real application but is heavily modified.</p><p>First we will look into the implementation of mentioned pattern with using Enums, match syntax and Interfaces and in further part, we can discuss extending it even more.</p><p><strong>Short explanation of example:</strong></p><p>We are building API project which will allow us to use one endpoint to fetch data from third-party providers (the same type of data). Let’s say there are 2 of these.</p><p>We need 2 Services (1 for each) which will handle data provider-specific logic since these differ due to different authentication method and responses. After all parsing is done, we want to return it to our caller.</p><p>Credentials for each of these providers are stored in DB (security measurements taken into consideration), so we need endpoint(s) that will allow us to point which data provider we want data from and which credentials to use (hence dynamic {id} below). In reality it is more complicated case but let’s keep it simple here.</p><p>We can implement 2 different endpoints for GET method, f.ex.</p><ol><li>https://ourhost.app/api/fetch/firstDataProvider/{id}/testData</li><li>https://ourhost.app/api/fetch/secondDataProvider/{id}/testData</li></ol><p>Next step is to implement Controller(s) for handling the requests.<br>Intuitive thing is to make 2 Controllers — one for each endpoint since these are for different Data Providers.</p><p><strong>But… Here comes usage of Factory Pattern:<br></strong>We can have 1 Controller that will recognise which data provider is requested, it will call Factory Class to get needed Service Instance which will handle the logic and then the Controller will return the response (or error…)</p><p><strong>Let’s define our interfaces</strong></p><pre>&lt;?php<br><br>namespace App\Interfaces\Services;<br><br>use App\Enums\DataProvidersEnum;<br>use Illuminate\Support\Collection;<br><br>/**<br>* Interface of a function parameter (can be for ValueObject, DTO <br>* or any custom object that will carry values and methods)<br>*/<br>interface ITestDataQuery<br>{<br>  public function myQueryMethod(): mixed;<br>}<br><br>/**<br> * Interface which needs to be implemented by all desirect Service Classes that are about to get instantiated.<br> */<br>interface IDebugDataService<br>{<br>    public function fetchTestData( ITestDataQuery $query ): Collection;<br>}<br><br>/**<br> * Let&#39;s make sure our Factory implements that interface, so we have clear contract for it.<br> * That will also allow easier manipulations/extending for classes expecting that interface<br> * As param&#39;s type<br> */<br>interface IServiceFactory {<br><br>    public function getDebugDataServiceInstance( DataProvidersEnum $enum ): IDebugDataService;<br><br>}</pre><p><strong>Let’s define our Enum:</strong></p><pre>&lt;?php<br><br>namespace App\Enums;<br><br>/**<br> * Let&#39;s use Enum for our data providers to make controlling easier<br> */<br>enum DataProvidersEnum: string<br>{<br>    case FIRST_DATA_PROVIDER = &#39;firstDataProvider&#39;;<br>    case SECOND_DATA_PROVIDER = &#39;secondDataProvider&#39;;<br>    case NOT_SUPPORTED_DATA_PROVIDER = &#39;notSupportedDataProvider&#39;;<br>}</pre><p><strong>Now it is time for our Services:</strong></p><pre>&lt;?php<br><br>namespace App\Services\DebugData;<br>use App\Interfaces\Services\IDebugDataService;<br>use App\Interfaces\Tools\ValueObjects\Queries\DebugData\ITestDataQuery;<br>use Illuminate\Support\Collection;<br><br>/**<br> * Our Service Class(es) must implement desired Interface to avoid surprises in Controllers.<br> * These can also extend the same class if needed (the Interface can be on parent).<br> */<br>class FirstDebugDataService implements IDebugDataService<br>{<br>    public function fetchTestData( ITestDataQuery $query ): Collection<br>    {<br>        // here goes your implementation....<br>        return collect();<br>    }<br><br>    // And your methods for the service...<br>}<br><br>class SecondDebugDataService implements IDebugDataService<br>{<br>    public function fetchTestData( ITestDataQuery $query ): Collection<br>    {<br>        // here goes your implementation....<br>        return collect();<br>    }<br><br>    // And your methods for the service...<br>}</pre><p>At that stage, we already know what Interfaces we are dealing with, each of our classes does implement the expected one (so we can apply other ‘design patterns’ on top of these in the future, if needed) and we also have 2 different Services with the same starting function which’s implementation is forced by Interface.<br>Thanks to that Controller knows what methods it can call.</p><p><strong>Let’s look at example of our Factory Class:</strong></p><pre>&lt;?php<br><br>namespace App\Factories\DebugData;<br><br>class ServiceFactory implements IServiceFactory<br>{<br><br>    /**<br>     * We could also use DI in here for Services when no parameters are required<br>     * That would also be a good thing for that code but let&#39;s make it a bit more flexible right away<br>     */<br>    public function __construct() {}<br><br>    /**<br>     * Use match on Enum and return new Instance of desired Service.<br>     * Beside only that one param, you might want to provide more params (best contracted by Interfaces)<br>     * since Services might expect some params.<br>     * Or you can extpect Service&#39;s methods to get some params, too.<br>     *<br>     * @param DataProvidersEnum $enum<br>     *<br>     * @return IDebugDataService<br>     */<br>    public function getDebugDataServiceInstance( DataProvidersEnum $enum ): IDebugDataService<br>    {<br>        return match ($enum) {<br>            DataProvidersEnum::FIRST_DATA_PROVIDER =&gt; $this-&gt;getFirstDebugDataService(),<br>            DataProvidersEnum::SECOND_DATA_PROVIDER =&gt; $this-&gt;getSecondDebugDataService(),<br>            default =&gt; throw new UnsupportedDataProviderException($enum), // In case we have some cases which we don&#39;t want to support...<br>        };<br>    }<br><br>    /**<br>     * These 2 methods below are protected because we don&#39;t want to allow direct access <br>     *<br>     * Also, if we find out at some point we need another version of that Factory,<br>     * but the old one still needs to be available for time being,<br>     * we can extend it and in the child class we can override these methods (f.ex. to require some params).<br>     *<br>     * That is quite common case when dealing with multiple versions of APIs<br>     *<br>     * @return IDebugDataService<br>     */<br>    protected function getFirstDebugDataService(): IDebugDataService<br>    {<br>        return new FirstDebugDataService();<br>    }<br><br>    protected function getSecondDebugDataService(): IDebugDataService<br>    {<br>        return new SecondDebugDataService();<br>    }<br>}</pre><p>So, what happens here?</p><ul><li>We make sure our class ServiceFactory implements IServiceFactory — that allows more flexibility thanks to using Interface and Parameter Type</li><li>We implement 2 protected methods: getFirstDebugDataService and getSecondDebugDataService <br>Doing it this way, allows us to override them in child classes. That might be handy when we need to develop next version of our code but the old one still needs to be available for some time</li><li>We implement getDebugDataServiceInstance which expects our DataProvidersEnum as parameter. Using Enum in here, makes sure we don’t make any typos and we have fixed list of case(s) we can use.<br>Next, we use match syntax on our Enum to discover which instance we want to return.<br>In case of case which we don’t have implementation for (for some reason), we want to throw Exception to inform Controller what is wrong and it needs to handle it.</li></ul><p><strong>Now, let’s have a look at our Controller handling request and using Factory:</strong></p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>class FetchDataController extends Controller<br>{<br>    /**<br>     * Use DI to have access to factory class right away<br>     *<br>     * @param IServiceFactory $dataProviderServiceFactory<br>     */<br>    public function __construct(<br>        protected readonly IServiceFactory $dataProviderServiceFactory = new ServiceFactory(),<br>    ) {}<br><br>    /**<br>     * In Laravel, you would get Request instance in here but let&#39;s not complicate it<br>     * for people who don&#39;t know Laravel.<br>     * Let&#39;s assume we get our DataProvider case right away in here<br>     *<br>     * @param DataProvidersEnum $dataProviderEnum<br>     */<br>    public function fetchTestData( DataProvidersEnum $dataProviderEnum ): JsonResponse<br>    {<br>        try {<br>            return response() // This is Laravel&#39;s built-in function. Use whatever fits your app<br>                -&gt;json(<br>                    $this-&gt;dataProviderServiceFactory<br>                        -&gt;getDebugDataServiceInstance($dataProviderEnum) // here we fetch our Service Instance<br>                        -&gt;fetchDebugData( // We know our Service implements particular Interface, so we can use method on it<br>                            new TestDataQuery(&#39;some data&#39;, &#39;goes here&#39;) // Instantiate our Query since Service method required it<br>                        )<br>                        -&gt;toArray() // this is because we get Laravel&#39;s Collection in here. Adjust to your app<br>                );<br><br>        } catch ( UnsupportedDataProviderException $e ) { // we got exception of unsupported data provider - handle it exclusively.<br>            return response()-&gt;json([&#39;error&#39; =&gt; &#39;Unsupported data provider.&#39;]);<br>        } catch( Exception $e ) { // some other exception - handle it as needed<br>            return response()-&gt;json([&#39;error&#39; =&gt; &#39;Some other error.&#39;]);<br>        }<br><br>    }<br>}</pre><p><strong>Let’s explain it a bit:</strong></p><ol><li>In our constructor, we use <strong>Class Constructor Property Promotion </strong>to have available our Factory Class as class attribute right away</li><li>We implement fetchTestData function which expects DataProvidersEnum as parameter for further giving it to our Factory.</li><li>We trigger getDebugDataServiceInstance method from the Factory to receive wanted instance of Service desired for requested third-party data provider.</li><li>Since we know that Service Instance implements IDebugDataService , we can safely call fetchDebugData method on it which is entry point for fetching data on specific way aligned to third-party data provider.<br>Since that moment, Service takes care of fetching data, parsing, validating etc. At the end, Service needs to return something to Controller</li><li>Now, Controller can return response in desired format.</li><li>In case of Exception — we have crafted new UnsupportedDataProviderException which we can use to recognise if very specific error occured. In case we try to use data provider which we have no Service implemented for, we can catch it and handle error on specific way.<br>In other case, we can catch other Exceptions and act accordingly (these can be also custom Exceptions f.ex. from Services etc.)</li></ol><p>By utilizing the Factory Pattern, we’ve constructed a streamlined, maintainable system capable of handling multiple data providers with ease. It not only enhances our application’s flexibility but also sets a robust foundation for future expansion. The Factory Pattern, with its ability to decouple instantiation logic, proves to be an indispensable tool in a developer’s toolkit.</p><h3><strong>So, what are benefits of using Factory Pattern?</strong></h3><ol><li><strong>We get centralised logic for instantiating objects</strong> which allows for re-using it in multiple places. Change to it can be done in one place instead of multiple locations.</li><li><strong>Our code is much easier to test.</strong> Imagine logic from Factory Class being implemented in Controller’s method. That adds multiple scenarios in tests only for that one function.<br>Then, also you might end up with multiple methods needing instantiating Service. Now you have multiple additional scenarios in multiple functions.</li><li>By implementing it on a bit more complicated way, <strong>you can extend Factory’s behaviour in one place when needed</strong>. Sure, in perfect world scenario you might want to have only one way to do things but real-life example: you need to instantiate object allowing calculations of budget for each year. Since each year there were changes, you end up with multiple options which might require different parameters. It is worth to spend a bit more time on making code flexible for long-term projects.</li><li><strong>Decoupling.</strong> The pattern decouples the client code from the concrete classes, promoting the use of interfaces or abstract classes. This loose coupling is beneficial for maintainability and scalability.</li><li><strong>Control over Object Creation.</strong> Factories can control the number of instances created, potentially implementing features like object pooling or singletons.</li></ol><h3>A few words at the end</h3><p>Using Design Patterns is beneficial for other developers who will be working on a project. It is much easier to recognise some of popular patterns used in the project instead of trying to understand somebody’s unique invention for common problems (and we know that is the case quite often).</p><p>While the Factory Pattern offers numerous advantages, it’s crucial to note that like any tool or pattern, <strong>it shouldn’t be used everywhere arbitrarily</strong>. It’s best suited for situations where there’s a clear benefit in centralizing the object creation process or when there’s a need for decoupling the client code from the specific classes being instantiated.</p><p>I have used Interfaces and Dependency Injection in this example. If you’re unfamiliar with these concepts, stay tuned for upcoming articles where we’ll dive deep into these topics.</p><p>Have you found this article helpful and want to keep me awake for writing more?<br>Here is your chance to get me a coffee: <a href="https://www.buymeacoffee.com/grzegorzlaT">https://www.buymeacoffee.com/grzegorzlaT</a></p><p>Greetings,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75f2de6f22e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constants vs. String Literals: Crafting Cleaner PHP Code.]]></title>
            <link>https://medium.com/@bluznierca1/constants-vs-string-literals-crafting-cleaner-php-code-63f4c4fee176?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f4c4fee176</guid>
            <category><![CDATA[constant]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 08:09:24 GMT</pubDate>
            <atom:updated>2023-11-07T15:30:17.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz5-KZtldlVA-bKUyTE7Lg.jpeg" /></figure><p>In the programming, especially in long-term projects, details do matter when it comes to clarity and maintainability of our code.<br>One such shift, often overlooked yet profound in its impact, is the choice between using String Literals and Constants.</p><p>At first, it might seem like stylistic preference but when we look deeper into that matter, we’ll find that this choice has far-reaching implications, affecting everything from code readability to refactoring ease.</p><p>In this article, we’ll embark on a journey through the PHP landscape, exploring the advantages of constants and understanding why they’re the secret ingredient to crafting cleaner, more robust code.</p><h4>The Case Against String Literals</h4><p>As we experience on daily basis, using string literals is just easy, fast and does not cause any additional complexity. <br>We use them to represent f.ex. keys in associative arrays, column names, filenames etc.</p><p>All seems great but once our project grows, our OOP approach becomes more complicated or when we write more tests, we might run into annoying issue while refactoring things (well, the ones who are not coding masters at least).</p><p>Let’s have a look at very basic code (done specifically to present some of the issues):</p><pre>&lt;?php<br><br>namespace App;<br><br>class MyStringLiteralExposeClass {<br>    <br>    public function getArrayWithNameAndType(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; &#39;Cool Name&#39;,<br>            &#39;type&#39; =&gt; &#39;CoolType&#39;<br>        ];<br>    }<br>    <br>}<br><br>class MyStringLiteralConsumerClass {<br>    <br>    public function __construct(<br>        protected string $name,<br>        protected MyStringLiteralExposeClass $myStringLiteralExposeClass = new MyStringLiteralExposeClass()<br>    ) {}<br>    <br>    public function displayNameAndType(): void<br>    {<br>        $nameTypeArray = $this-&gt;myStringLiteralExposeClass-&gt;getArrayWithNameAndType();<br>        echo sprintf(<br>            &#39;The name provided in construct is %s, and extracted name %s which has type %s&#39;,<br>            $this-&gt;name,<br>            $nameTypeArray[&quot;name&quot;],<br>            $nameTypeArray[&#39;type&#39;]<br>        );<br>    }<br>}<br><br>$myStringLiteralConsumerClass = new MyStringLiteralConsumerClass(&#39;random name&#39;);<br>$myStringLiteralConsumerClass-&gt;displayNameAndType();</pre><p>At first look all seems nice and easy (because it is in here) but…</p><p>Let’s imagine scenario where we realise that for some reason we need to update name key inside of <br>MyStringLiteralExposeClass-&gt;getArrayWithNameAndType function to be now specificName .</p><p>If you use IDE’s search function, only in that file you get 16(!) hits for searching name .<br>Yes, you can search for &#39;name&#39; and you get (watch out!) only 1 hit.<br>Then, another option in PHP — you can search for &quot;name&quot; and you get also 1 hit.</p><p>Now imagine that these classes are in separated files and there are 50 different classes containing usage of key name in them but not all come from the same function, so not all will be the subject to update.<br>Now, I feel sorry for anyone who needs to find it, check context to define if that is what you need and won’t make <strong>typo</strong> while changing (yes, that is another common issue).</p><h4>How can constant help in that case?</h4><p>Let’s have a look at updated code example and analyse it:</p><pre>&lt;?php<br><br>namespace App;<br><br>class MyStringLiteralExposeClass {<br><br>    // Yes, that needs to be public to be accessible.<br>    public const PARAM_NAME = &#39;name&#39;;<br>    public const PARAM_TYPE = &#39;type&#39;;<br><br>    public function getArrayWithNameAndType(): array<br>    {<br>        return [<br>            self::PARAM_NAME =&gt; &#39;Cool Name&#39;,<br>            self::PARAM_TYPE =&gt; &#39;CoolType&#39;<br>        ];<br>    }<br><br>}<br><br>class MyStringLiteralConsumerClass {<br><br>    public function __construct(<br>        protected string $name,<br>        protected MyStringLiteralExposeClass $myStringLiteralExposeClass = new MyStringLiteralExposeClass()<br>    ) {}<br><br>    public function displayNameAndType(): void<br>    {<br>        $nameTypeArray = $this-&gt;myStringLiteralExposeClass-&gt;getArrayWithNameAndType();<br>        echo sprintf(<br>            &#39;The name provided in construct is %s, and extracted name %s which has type %s&#39;,<br>            $this-&gt;name,<br>            $nameTypeArray[MyStringLiteralExposeClass::PARAM_NAME],<br>            $nameTypeArray[MyStringLiteralExposeClass::PARAM_TYPE]<br>        );<br>    }<br>}<br><br>$myStringLiteralConsumerClass = new MyStringLiteralConsumerClass(&#39;random name&#39;);<br>$myStringLiteralConsumerClass-&gt;displayNameAndType();</pre><p><strong>What happens in here?</strong></p><ol><li>We define public const PARAM_NAME inside of our MyStringLiteralExposeClass , so it is accessible by using :: in other classes.</li><li>We use that constant in our getArrayWithNameAndType to represent key.</li><li>Inside of MyStringLiteralConsumerClass , after getting array, we use MyStringLiteralExposeClass::PARAM_NAME as a key to extract value from associative array.</li></ol><p>Let’s again imagine scenario where we realise that for some reason we need to update name key inside of <br>MyStringLiteralExposeClass-&gt;getArrayWithNameAndType function to be now specificName but with updated code.</p><p>Just use your IDE to find usage of PARAM_NAME constant and enjoy list of all placements where that is being used without worrying about context.</p><p>In that case, our life got easier for 3 scenarios:</p><ol><li>When we only need to change value for that constant — we just do it in one place.</li><li>If for some reason it makes sense to change name of that constant along with its value — again, you got all occurrences of its usage.</li><li>We do not need to worry about typos which can easily happen while using string literals (even if happened, we update one place).</li></ol><h4>How about some more real life example?</h4><p>I am going to use Laravel as that is currently framework I am using on daily basis (although still thinking Symfony is great) and actually I find concept of using constants exceptionally useful for not very small projects.</p><p><strong>I am going to cover 2 use-cases:</strong></p><ol><li>Using constants for representing column names thorough the project</li><li>Using constants for representing arrays/collection keys thorough the project</li></ol><p><strong>Let’s dive into using constants for column names</strong></p><p>First, we will define model in which we use our constants.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>class User<br>{<br>    public const TABLE_NAME = &#39;users&#39;;<br>    <br>    public const COLUMN_ID = &#39;id&#39;;<br>    public const COLUMN_NAME = &#39;name&#39;;<br>    public const COLUMN_EMAIL = &#39;email&#39;;<br>    public const COLUMN_PASSWORD = &#39;password&#39;;<br>    <br>    // Updated version with constants<br>    protected $fillable = [<br>        self::COLUMN_NAME,<br>        self::COLUMN_EMAIL,<br>        self::COLUMN_PASSWORD,<br>    ];<br><br>    // Version with string literals (usual one)<br>    protected $fillable = [<br>      &#39;name&#39;, &#39;email&#39;, &#39;password&#39;<br>    ]<br><br>    // Updated version with constants<br>    protected $hidden = [<br>        self::COLUMN_PASSWORD,<br>    ];<br><br>    // Version with string literals (usual one)<br>    protected $hidden = [<br>      &#39;pasword&#39; // &lt;- SEE THE TYPO? - now the password will be exposed until fixed.<br>    ]<br>}</pre><p>As you can see, I am using quite descriptive naming for constants:</p><ul><li>TABLE_NAME — representing (surprise!) table name</li><li>COLUMN_{columnName} — representing (again, surprise!) column name.</li></ul><p>These constants are being used instead of string literals already in the Model but that is just a beginning. So, let’s look at migrations:</p><pre>&lt;?php<br><br>use App\Models\User;<br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    public function up(): void<br>    {<br>        /**<br>         * UPDATED VERSION WITH CONSTANTS - all have source in one place.<br>         * Have you deleted some constant in Model but forgot to delete from here? You will get expected error<br>         */<br>        Schema::create(User::TABLE_NAME, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(User::COLUMN_NAME);<br>            $table-&gt;string(User::COLUMN_EMAIL)-&gt;unique();<br>            $table-&gt;string(User::COLUMN_PASSWORD);<br>            $table-&gt;timestamps();<br>        });<br><br>        /**<br>         * Usual version with string literals where typos are just beginning.<br>         * Have you forgotten to delete some column in DB in here? Let it hang until it is somehow discovered<br>         */<br>        Schema::create(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>            $table-&gt;string(&#39;password&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    public function down(): void<br>    {<br>        Schema::dropIfExists(User::TABLE_NAME);<br><br>        // imagine typo here and deleting different table...<br>        Schema::dropIfExists(&#39;users&#39;);<br>    }<br>};</pre><p>As we can see, we can easily use constants defined inside Model also here.<br>Do you need to change Table Name or some Column Name? Just do it in the model and that is it.</p><p>But, it would not be beneficial if that was all… <strong>Let’s explore how it can be useful in our Request Validation</strong>:</p><pre>&lt;?php<br><br>namespace App\Http\Requests\User;<br><br>use App\Models\User;<br><br>class CreateUserRequest extends FormRequest<br>{<br>    public function rules(): array<br>    {<br>        $allParams = $this-&gt;all();<br><br>        /**<br>         * one of scenarios is we want body request to contain JSON with column names as keys.<br>         * In that case, using constant make it much easier becase again, you control everything from one place.<br>         */ <br>        return [<br>            User::COLUMN_NAME =&gt; [<br>                &#39;required&#39;,<br>                &#39;string&#39;,<br>                &#39;min:2&#39;<br>            ],<br>            User::COLUMN_EMAIL =&gt; [<br>                &#39;required&#39;,<br>                &#39;email&#39;,<br>                Rule::unique(<br>                    User::TABLE_NAME,<br>                    User::COLUMN_EMAIL<br>                )-&gt;ignore($allParams[User::COLUMN_ID]), // also used as array key<br>            ],<br>            User::COLUMN_PASSWORD =&gt; [<br>                &#39;required&#39;,<br>                &#39;string&#39;,<br>                &#39;confirmed&#39;,<br>                &#39;min:16&#39;,             // must be at least 16 characters in length<br>                &#39;regex:/[a-z]/&#39;,      // must contain at least one lowercase letter<br>                &#39;regex:/[A-Z]/&#39;,      // must contain at least one uppercase letter<br>                &#39;regex:/[0-9]/&#39;,      // must contain at least one digit<br>                &#39;regex:/[@$!%*#?&amp;-_]/&#39;, // must contain a special character<br>            ],<br>        ];<br>    }<br>}</pre><p>As visible in the example code, we expect our body request to contain payload with column names used as keys. Inside of Request Class , we can simply use our Model’s constants and reduce our list of worries to minimum.</p><p>But, to see it being even more powerful in big repos, let’s explore another usage: this time we will have UserQuery Class which will be responsible for building data delivered to query database (not covering in this article usage of it but at some point I will write one).</p><pre>&lt;?php<br><br>namespace App\Tools\ValueObjects\Queries\User;<br><br>class CreateUserQuery<br>{<br>    public function __construct(<br>        private readonly string    $name,<br>        private readonly string    $email,<br>        private readonly string   $password<br>    ) {}<br><br>    public function getName(): string<br>    {<br>        return $this-&gt;name;<br>    }<br>    <br>    public function getEmail(): string<br>    {<br>        return $this-&gt;email;<br>    }<br><br>    public function getHashedPassword(): string<br>    {<br>        return Hash::make( $this-&gt;password );<br>    }<br><br>    /**<br>     * That function is responsible for creating array of columns which we want to use to create Entity<br>     * And assign values to them.<br>     * It makes sure we don&#39;t update unwanted columns.<br>     * <br>     * @return array<br>     */<br>    public function getFillableData(): array<br>    {<br>        return array_filter([<br>            User::COLUMN_NAME =&gt; $this-&gt;getName(),<br>            User::COLUMN_EMAIL =&gt; $this-&gt;getEmail(),<br>            User::COLUMN_PASSWORD =&gt; $this-&gt;getHashedPassword(),<br>        ]);<br>    }<br>}</pre><p>How is that significant? Our getFillableData method returns array with columns used as keys and values assigned to them. That way, we don’t need to worry about typos because constants are immutable.</p><p>Since real benefit of using constants instead of string literals grows along with code base, we can use that concept also in Factory in Laravel:</p><pre>&lt;?php<br><br>namespace Database\Factories;<br><br>class UserFactory extends Factory<br>{<br>    /**<br>     * Define the model&#39;s default state.<br>     *<br>     * @return array&lt;string, mixed&gt;<br>     */<br>    public function definition()<br>    {<br>        return [<br>            User::COLUMN_NAME =&gt; fake()-&gt;name(),<br>            User::COLUMN_EMAIL =&gt; fake()-&gt;safeEmail(),<br>            User::COLUMN_PASSWORD =&gt; &#39;$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi&#39;, // password<br>        ];<br>    }<br>}</pre><p>Again, we operate on constants. Changing value inside of the model will cover every single usage of it, so we don’t need to waste time on playing detective.</p><p>As all developers using Laravel know, when dealing with models, you can access Model attributes (columns) directly and in this case, <strong>constants will require a bit of additional work </strong>(please, ignore breaking SRP and not dealing with Exception but I want to focus on matter):</p><pre>&lt;?php<br><br>class MyModelConstantClass {<br>  <br>  /**<br>  * Here we just fetch model (could use findOrFail() method and handle Exception...<br>  * And we use the easiest way offered by Laravel to fetch user&#39;s name<br>  */<br>  public function usualUsageOfModelAttributes(): void<br>  {<br>    $user = User::find(1);<br>    echo sprintf(<br>      &#39;User name is: %s&#39;,<br>      $user-&gt;name // in that case, using constants is no-go<br>    );<br>  }<br><br>  /**<br>  * Here is example of retrieving User&#39;s name with using constant<br>  * As presented, constant COLUMN_NAME is defined in User Model<br>  */<br>  public function usageOfConstantToGetModelAttributes(): void<br>  {<br>    $user = User::find(1);<br>    echo sprintf(<br>      &#39;User name is: %s&#39;,<br>      $user-&gt;getAttribute(User::COLUMN_NAME) // in general, I find using getAttribute() much better...<br>    )<br>  }<br>}</pre><p>In that case, the easy way is replaced with slightly more complicated one and at first it does not seem like it can bring any profit but, based on my own experience, I am happy when somebody decided to put extra effort and I can locate needed attribute without pulling my hair out.</p><p>These were only a few cases where some of the ‘string’ would be repeated throughout the whole codebase. Imagine more of these to be used in Services, Controllers, Tests etc… List grows but by using constants you can easily find every single occurrence of constant with IDE.</p><p>I think that it is enough get get grasp of the concept, so…</p><p><strong>Let’s now look into Using constants for representing arrays/collection keys thorough the project</strong></p><p>That is another, very basic example of how we can use constants but I want to show that this can also make code look quite uglier (kind of like in example with fetching Model’s attributes), so not everything is just perfect, especially when it comes to the length of lines.</p><pre>&lt;?php<br><br>namespace Database\Factories;<br><br>/**<br> * Let&#39;s not worry about Exception in here...<br> */<br>class MyConstantExporterClass<br>{<br>    public const KEY_FIRST_DATA_PROVIDER_RESPONSE = &#39;firstDataProviderResponse&#39;;<br>    public const KEY_SECOND_DATA_PROVIDER_RESPONSE = &#39;secondDataProviderResponse&#39;;<br><br>    public function gatherResponses(): array {<br>        // ... here I have code to gather responses...<br><br>        /**<br>         * Yes, we could use Value Object or DTO here which would make sense,<br>         * but for that example we will keep it simple<br>         */<br>        return [<br>            // let&#39;s pretend the values are defined... :)<br>            self::KEY_SECOND_DATA_PROVIDER_RESPONSE =&gt; $firstResponse,<br>            self::KEY_SECOND_DATA_PROVIDER_RESPONSE =&gt; $secondResponse<br>        ];<br>    }<br>}<br><br>class MyConstantImporterClass<br>{<br>    public function __construct(<br>        protected MyConstantExporterClass $constantExporterClass = new MyConstantExporterClass()<br>    ) {}<br><br>    public function handleResponses()<br>    {<br>        $responses = $this-&gt;constantExporterClass-&gt;gatherResponses();<br><br>        $this<br>          -&gt;transformFirstDataProviderResponse(<br>            $responses[MyConstantExporterClass::KEY_FIRST_DATA_PROVIDER_RESPONSE]<br>          )<br>          -&gt;transformSecondDataProviderResponse(<br>            $responses[MyConstantExporterClass::KEY_SECOND_DATA_PROVIDER_RESPONSE]<br>          );<br><br>        return $responses;<br>    }<br><br>    protected function transformFirstDataProviderResponse( array &amp;$response ): self<br>    {<br>        // some transformation happens...<br><br>        return $this;<br>    }<br><br>    protected function transformSecondDataProviderResponse( array &amp;$response ): self<br>    {<br>        // some transformation happens...<br><br>        return $this;<br>    }<br>}<br><br>$myConstantImporterClass = new MyConstantImporterClass;<br>$responses = $myConstantImporterClass-&gt;handleResponses();<br><br>dd(<br>    $responses[MyConstantExporterClass::KEY_FIRST_DATA_PROVIDER_RESPONSE],<br>    $responses[MyConstantExporterClass::KEY_SECOND_DATA_PROVIDER_RESPONSE]<br>);</pre><p>As visible — sometimes constants can get really long name if we want to keep it descriptive (although we don’t have to…?). It is up to the developer to decide if sometimes it is worth to sacrifice visibility (although it is not the worst it can be) for usability.</p><p>One way to deal with that is reducing name of class we are dealing with by using <strong>alias.</strong></p><h3>Summary: Why Constants Shine Over String Literals</h3><p>When coding in PHP, using constants over string literals brings big benefits:</p><ul><li><strong>Clearer Code:</strong> Constants like MyModel::COLUMN_NAME instantly tell us more than just a plain &#39;name&#39;. We know it&#39;s tied to MyModel, so it&#39;s easier to understand what&#39;s going on.</li><li><strong>Easy Updates:</strong> Need to change a name or value? With constants, change it in one place and you’re done. No risky global searches or missed spots.</li><li><strong>Fewer Mistakes:</strong> It’s easy to mistype a string. But with constants, your coding tool will likely catch the mistake for you.</li><li><strong>Quick Searches:</strong> Using tools like PhpStorm, you can find where a constant is used in seconds. It’s a real time-saver.</li><li><strong>Built-in Guide:</strong> Constants also act like mini-guides, helping others get what you were aiming for in your code.</li></ul><p>In short, while both have their uses, constants offer a clearer, safer, and more efficient way to code in PHP.</p><p>Because why to sacrifice a few minutes now when we can spend a few hours debugging later…</p><p>Have you found this article helpful and want to keep me awake for writing more?<br>Here is your chance to get me a coffee: <a href="https://www.buymeacoffee.com/grzegorzlaT">https://www.buymeacoffee.com/grzegorzlaT</a></p><p>Greetings,<br>Grzegorz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f4c4fee176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Templating API Calls and More: Exploring the Template Method Pattern in PHP]]></title>
            <link>https://medium.com/@bluznierca1/templating-api-calls-and-more-exploring-the-template-method-pattern-in-php-18ec80306e7?source=rss-8a2d31b5e9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/18ec80306e7</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[template-method-pattern]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Grzegorz Lasak (Gregster)]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 15:30:54 GMT</pubDate>
            <atom:updated>2023-08-31T15:30:54.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4uvWJ3iFAUxIKdHQiTSdg.jpeg" /></figure><p>Have you ever felt ensnared in a web of code that’s repetitive yet just distinct enough to resist a straightforward refactor? The sort where adding a new class — whether for a third-party API integration, custom workflow, or some other cool thing — feels like déjà vu? It’s the ‘same same, but different’ conundrum.</p><p>One way to solve it is using Template Method Pattern — our orchestra’s conductor, ensuring each musical piece (or, in our coding world, class) maintains a consistent rhythm. At the same time, it allows individual instruments (methods) their spotlight moments. In PHP, this translates to crafting a structured skeleton for your classes, enabling child classes to add unique touches without having to redo the entire symphony.</p><h4>What is the Template Method Pattern?</h4><p><strong>Technical Definition:</strong> A behavioral design pattern that defines the program skeleton in an algorithm but delays some steps to subclasses.</p><p>Well… Let’s define it with some analogy to more day-to-day example.</p><p><strong>Analogy: </strong>Imagine building a house. There’s a general blueprint that dictates the order in which things need to be done — laying the foundation, putting up walls, installing the roof, etc. However, the specifics, like the colour of the walls or the type of roof tiles, can differ based on individual preferences.</p><p><strong>In Application: </strong>With the Template Method Pattern, our blueprint is the ‘template method.’ It outlines the sequence in which methods (building steps) should be executed. The specifics of each step — like the wall colour or roof type — are then defined in our individual house designs (subclasses).</p><h4>Why use the Template Method Pattern? Let’s dive into real example.</h4><p>The code example is based on code used in real app (although heavily modified to cover the topic and not expose sensitive info) which means some of the things (f.ex. usage of Interfaces, VOs etc.) will not be explained in this article.<br>Code is written in Laravel 10, so some of the methods are provided by it.<br>Also, please, pay attention to comments in code examples where I have included more descriptions.</p><p>Our story’s hero, Dev Greg, was tasked with implementing code to gather data from multiple third-party API providers.<br>After spending some time on reading very well described documentations for these APIs (we know how that goes), it came out that both require a request to obtain the Token, followed by a second one to fetch data (where Token must be attached).</p><p>After completing the initial implementation (first solve the issue, then refactor ;)), he ended up with 2 Services which had almost identical way of autohorisation and authentication while fetching data:<br>1. Send request with Integration-specific data for authorisation to receive Token<br>2. Extract Token from response and keep it<br>3. Send request to fetch data with attached Token and Integration-specific setup (Headers, body request etc.).</p><p>These 2 Services contained a lot of repeated code but at the same time there were some Integration-specific caveats which made it impossible to just share methods served from Parent class:</p><ul><li>Each integration expected different set of keys, some encoded in specific manner, attached in (also different) Headers for the authorization, different URLs, Request types etc.</li><li>One integration was REST (supporting different paths and URL query parameters), another one was using GraphQL, so request body had to be crafted on very different way but all going with the same Request Method and URL (except authentication).</li></ul><p>These 2 points made it already clear that Template Method Pattern will be useful in here since it allows to force the rhythm and flow (like symphony’s conductor) and will allow subclasses to have methods which will prepare requests on expected way without tempering with already established order.</p><p>Let’s look into the code which is representing Service Abstract Class orchestrating the flow and forcing methods that subclasses have to implement:</p><pre>&lt;?php<br><br>abstract class AbstractTemplateMethodPatternExampleService<br>{<br>    protected ?IRequestData $requestData = null; // IRequestData is Interface representing all data to be used in Request (not covered in this article in detail)<br><br>    protected IntegrationModel $integration; // We need to have Integration set at this level (by subclass). It contains all data required for Integration to get access to data<br><br>    // Custom Service which we don&#39;t cover here. Could be original Guzzle Client instead<br>    public function __construct(<br>        protected GuzzleService $guzzleService = new GuzzleService()<br>    ) {}<br><br>    /**<br>     * Each subclass needs to SET RequestVO because it will contain different<br>     * Body Request, Method and URL Depended on third-party API Provider<br>     * but each has to extend IRequestData (Interface) to make sure that<br>     * Contract is fulfilled before calling some of expected methods<br>     *<br>     * @return IRequestData<br>     * @throws \Exception<br>     */<br>    final protected function getRequestVO(): IRequestData<br>    {<br>        if ( ! $this-&gt;requestData ) {<br>            throw new \Exception(&#39;RequestVO is not set!&#39;);<br>        }<br><br>        return $this-&gt;requestData;<br>    }<br><br>    /**<br>     * Force Subclass to Return Data Provider Name which is Enum (from our own list), so it cannot be random string<br>     *<br>     * @return DataProvidersEnum<br>     */<br>    protected abstract function getDataProviderName(): DataProvidersEnum;<br><br>    /**<br>     * Each customer credentials are separated model/repository.<br>     * Handle logic of extracting authentication data accordingly<br>     * and return IAuthenticationData so headers can be controlled from one place.<br>     *<br>     * @param IntegrationModel $integration<br>     *<br>     * @return IAuthenticationData<br>     */<br>    protected abstract function getAuthenticationData(<br>        IntegrationModel $integration<br>    ): IAuthenticationData; // it will make sure we can request prepared array with authentication details<br><br>    /**<br>     * Fetch correct data provider credentials and set as class attributes<br>     * for easier reusing.<br>     *<br>     * Some Integrations do require custom logic before we can use it, so subclass needs to take care of it<br>     *<br>     * @param IntegrationModel $integration<br>     *<br>     * @return $this<br>     */<br>    protected abstract function setIntegration( IntegrationModel $integration ): self;<br><br>    /**<br>     * Perform authentication request with data provider system and set all required class attrs.<br>     * Recommended to set customer credentials, too.<br>     * Beside, set f.ex. Bearer Token or any obj needed for authorization request so can be reused.<br>     *<br>     * Since each Integration might have it done on different way, subclass has to handle it. It can still reuse GuzzleService provided via DI<br>     *<br>     * @param IntegrationModel $integration<br>     *<br>     * @return $this<br>     */<br>    protected abstract function authenticate( IntegrationModel $integration ): self;<br><br>    /**<br>     * Combine request options with authorization headers.<br>     *<br>     * Each Data Provider requires different setup for Authorization, so subclass needs to take care of that<br>     *<br>     * @param IRequestData $request<br>     *<br>     * @return array<br>     */<br>    protected abstract function mergeRequestOptionsWithAuthorization(<br>        IRequestData $request<br>    ): array;<br><br>    /**<br>     * Validate access token if issued. Default fallback to false.<br>     *<br>     * Each Integration might have different requirement for checking if Token is valid.<br>     * F.ex. it might be checking time (so we don&#39;t needs to make authentication requests if our token is still valid)<br>     *<br>     * @param bool $throwException<br>     *<br>     * @return bool<br>     */<br>    protected function isAccessTokenValid( bool $throwException = false ): bool<br>    {<br>        return false;<br>    }<br><br>    protected function getIntegration(): ?IntegrationModel<br>    {<br>        return $this-&gt;integration;<br>    }<br><br>    /**<br>     * Some Exceptions are not supposed to be caught since Controller will take care of them.<br>     * It makes sure to check existance of Request responsible for fetching data,<br>     * preparing and sending request.<br>     * Subclasses should not be able (at least in that scenario) modify it, so it if final class.<br>     *<br>     * @param IRequestData $request<br>     * @return Response|null<br>     *<br>     * @throws DataProviderRequestException<br>     * @throws GuzzleException<br>     */<br>    final protected function sendRequest( IRequestData $request ): ?Response<br>    {<br><br>        $this-&gt;isAccessTokenValid();<br><br>        try {<br>            return $this-&gt;guzzleService-&gt;sendRequest(<br>                $request,<br>                $this-&gt;mergeRequestOptionsWithAuthorization($request)<br>            );<br><br>        } catch ( \Exception $e ) {<br>            throw new DataProviderRequestException($request, $e-&gt;getMessage());<br>        }<br>    }<br><br>    /**<br>     * Our symphony&#39;s conductor in here ;)<br>     *<br>     * Each Integration might require some additional steps (f.ex. some integrations required multiple requests<br>     * to gather required data), so allow subclass override it.<br>     *<br>     * It is not private method because it would not be usable by subclasses (at least not directly).<br>     * It is not public method because we don&#39;t want to allow it to be used outside of context.<br>     *<br>     * This could be marked as a final class, and it probably should be but some integrations might need to implement some corner cases logic<br>     *<br>     * @param IDebugDataQuery $query<br>     * @return Collection<br>     * @throws GuzzleException<br>     */<br>    protected function fetchData(<br>        IDebugDataQuery $query,<br>    ): ?array {<br>        $integration = $query-&gt;getIntegration();<br>        $dataProviderResponse = null;<br><br>        try {<br>            $response = $this<br>                -&gt;authenticate( $integration ) // authenticate is forced to be implemented in subclasses<br>                -&gt;sendRequest( $this-&gt;getRequestVO() ) // sendRequest is defined in current class but can be extended if needed<br>                -&gt;getBody()<br>                -&gt;getContents();<br><br>            $dataProviderResponse = JsonHelper::decodeJson($response);<br>        } catch( DataProviderRequestException ) { // already logged, just proceed<br>        } catch( JsonException $e ) {<br>            LogHelper::logDataProvider(<br>                sprintf(<br>                    &quot;Issue %s %s data response for integration [%s]: %s&quot;,<br>                    $this-&gt;getDataProviderName()-&gt;value, // request to which Data Provider failed?<br>                    (new ReflectionClass($query))-&gt;getShortName(), // different queries fetch different data<br>                    $integration-&gt;getAttribute(&#39;id&#39;), // so we know which Integration failed since there are many<br>                    $e-&gt;getMessage()) // and our message for later debugging<br>            );<br>        }<br><br>        return $dataProviderResponse;<br>    }<br>}</pre><p>Here, I’d like to highlight two main points:</p><ol><li><strong>Usage of </strong>protected abstract method<strong> followed by method signature:</strong><br>These methods intentionally lack a body.<br>That way we can force subclass to implement protected method (unlike public methods by using Interface) which in that case is desired.<br>It is important to note that it is possible only inside of abstract class</li><li><strong>Body of </strong>protected function fetchData<strong> method — that is where Template Method Pattern’s essence is kept:<br>- </strong>We trigger authenticate method which is example of method from 1st point.<br>- Next, we call sendRequest method with instance of IRequestData Class as parameter which needs to be provided by subclass.<br>- At next stage, we check if Token is valid (validation of Token needs to be performed by subclass)<br>- If all is good so far, we mergeRequestOptionsWithAuthorization forced to be implemented by subclass and we send request.</li></ol><p>Let’s look into example implementation of a class which will use that Pattern and will implement all must-have methods:</p><pre>&lt;?php<br>/**<br> * Class taking care of authenticating with API provider&#39;s system.<br> *<br> */<br>class MyClassForFetchingDataService extends AbstractDebugDataAuthService<br>{<br>    /** Object representing Bearer Auth Data with its own logic depended on API Integration. */<br>    protected IBearerAuthenticationData $bearerAuthenticationData;<br><br>    /**<br>     * Implementation of must-have method to know which Data Provider we are dealing with<br>     * @return DataProvidersEnum<br>     */<br>    protected function getDataProviderName(): DataProvidersEnum<br>    {<br>        return DataProvidersEnum::SOME_PROVIDER;<br>    }<br><br>    /**<br>     * Custom method Integration-Specific to build URL<br>     * @param string $customerName<br>     * @return string<br>     */<br>    public function getAuthUrl(string $customerName): string<br>    {<br>        if ( !($authUrl = env(&#39;REQUIRED_AUTH_URL&#39;)) ) {<br>            throw new MissingEnvParamException(&#39;Auth URL not found!&#39;);<br>        }<br><br>        return str_replace(<br>            &#39;##authUrlHolder##&#39;,<br>            $customerName,<br>            $authUrl<br>        );<br>    }<br><br>    /**<br>     * Object representing Bearer Auth Data - <br>     * <br>     * @param IBearerAuthenticationDataVO $authData<br>     *<br>     * @return $this<br>     */<br>    protected function setBearerAuthenticationData(<br>        IBearerAuthenticationData $authData<br>    ): self {<br>        $this-&gt;bearerAuthenticationData = $authData;<br><br>        return $this;<br>    }<br><br>    /**<br>     * Let&#39;s have option to get that object<br>     * <br>     * @return IBearerAuthenticationData<br>     */<br>    protected function getBearerAuthenticationData(): ?IBearerAuthenticationData<br>    {<br>        return $this-&gt;bearerAuthenticationData;<br>    }<br><br>    /**<br>     * Implementation of must-have method and custom logic for validating Token<br>     * @param bool $throwException<br>     *<br>     * @return bool<br>     *<br>     * @throws AuthenticationTokenNotIssuedException<br>     */<br>    protected function isAccessTokenValid( bool $throwException = true ): bool<br>    {<br>        if (<br>            isset($this-&gt;bearerAuthenticationData) &amp;&amp;<br>            !$this-&gt;getBearerAuthenticationData()-&gt;isAccessTokenExpired()<br>        ) {<br>            return true;<br>        }<br><br>        if ( $throwException ) {<br>            throw new AuthenticationTokenNotIssuedException(<br>                $this-&gt;getDataProviderName()<br>            );<br>        }<br><br>        return false;<br>    }<br><br>    /**<br>     * Implementation of must-have method.<br>     * Integration-specific logic for building Auth Query (custom object, not covered in that article)<br>     * @param IntegrationModel $integration<br>     *<br>     * @return IAuthenticationData<br>     */<br>    protected function getAuthenticationData( IntegrationModel $integration ): IAuthenticationData<br>    {<br>        return new MyAuthDataQuery(<br>            $integration-&gt;getAttribute(MyIntegrationModel::COLUMN_DATA_CLIENT_ID),<br>            $integration-&gt;getAttribute(MyIntegrationModel::COLUMN_DATA_SECRET_KEY),<br>        );<br>    }<br><br>    /**<br>     * Not in factory due to fixed context of column names per provider.<br>     * Validate if we have all required data for authenticating in third-party API Provider<br>     * Set Integration model (for further reference)<br>     *<br>     * @param IntegrationModel $integration<br>     *<br>     * @return $this<br>     *<br>     * @throws MissingAuthCredentialsException<br>     */<br>    protected function setIntegration( IntegrationModel $integration ): self<br>    {<br>        if (<br>            !empty($integration-&gt;getAttribute(MyIntegrationModel::COLUMN_DATA_CLIENT_ID)) &amp;&amp;<br>            !empty($integration-&gt;getAttribute(MyIntegrationModel::COLUMN_DATA_SECRET_KEY))<br>        ) {<br>            $this-&gt;integration = $integration;<br><br>            return $this;<br>        }<br><br>        throw new MissingAuthCredentialsException(<br>            $this-&gt;getDataProviderName(),<br>            $integration-&gt;getAttribute(MyIntegrationModel::COLUMN_ID)<br>        );<br>    }<br><br>    /**<br>     * Implementation of must-have method.<br>     * Authenticate and obtain Token which will be used later to fetch data<br>     * <br>     * @param IntegrationModel $integration<br>     *<br>     * @return $this<br>     *<br>     * @throws AuthenticationTokenNotIssuedException<br>     * @throws DataProviderAuthenticationException<br>     * @throws GuzzleException<br>     * @throws MissingAuthCredentialsException<br>     * @throws MissingEnvParamException<br>     */<br>    protected function authenticate(MyIntegrationModel $integration ): self<br>    {<br>        // if token still valid, use it. Create new one otherwise<br>        if ( $this-&gt;isAccessTokenValid(false) ) return $this;<br><br>        $this-&gt;setIntegration( $integration );<br><br>        $url = $this-&gt;getAuthUrl($integration-&gt;getAttribute(&#39;customer_name&#39;));<br><br>        try {<br>            $response = $this-&gt;guzzleService-&gt;getClient()-&gt;request(<br>                &#39;POST&#39;,<br>                $url,<br>                $this<br>                    -&gt;getAuthenticationData($this-&gt;getIntegration())<br>                    -&gt;getRequestOptionsArray()<br>            );<br><br>            $decodedResponse = JsonHelper::decodeJson(($response-&gt;getBody()-&gt;getContents()));<br><br>            $this-&gt;setBearerAuthenticationData(<br>                new IBearerAuthenticationDataVO(<br>                    $decodedResponse[IBearerAuthenticationData::PARAM_ACCESS_TOKEN],<br>                    $decodedResponse[IBearerAuthenticationData::PARAM_EXPIRES_IN],<br>                )<br>            );<br>        } catch ( \Exception $e ) {<br>            throw new DataProviderAuthenticationException(<br>                $this-&gt;getDataProviderName(),<br>                $integration-&gt;getAttribute(MyIntegrationModel::COLUMN_ID),<br>                $e-&gt;getMessage()<br>            );<br>        }<br><br>        return $this;<br>    }<br><br>    /**<br>     * Implementation of must-have method.<br>     * After we are authenticated, this will take care of merging authorization requirements with request data<br>     * to be able to get what we need.<br>     * <br>     * @param IRequestData $request<br>     * @return array<br>     */<br>    protected function mergeRequestOptionsWithAuthorization( IRequestData $request ): array<br>    {<br>        return array_merge(<br>            $request-&gt;getRequestOptionsArray(),<br>            (new MyAuthorizationDataQuery(<br>                $this-&gt;getBearerAuthenticationData(),<br>            ))-&gt;getRequestOptionsArray()<br>        );<br>    }<br><br>    /**<br>     * Attempt to fetchData which will be triggering orchestrated process coordinated by parent class.<br>     * @return array|null<br>     */<br>    public function fetchMyDesiredData(): ?array {<br>        return $this-&gt;fetchData(new MyDebugDataQuery());<br>    }<br>}</pre><p>As we can see, the subclass does implement all ‘must-have’ methods and also includes Integration-specific ones.<br>Most of the methods are protected due to the fact that I would not like any Controller (or another Service using that one) tempt with the data which right now is being set on specific way, so public methods available in our Service should be the only proxies between our app and third-party API provider.</p><h4>A few last words on the topic</h4><p>I hope that the example of API integrations with PHP shows the power of Template Method Pattern.</p><p>We learned that by creating a blueprint — much like an architect does for houses — we can lay down the general sequence of events, and then let the specific implementations bring in their unique flavours. <br>This ensures that the core logic remains unaltered, while specific implementations can decide about ‘colour of the walls, type of tails etc.’</p><p>I hope you will find it useful and be able to use that pattern in your projects since implementation of common coding techniques makes life easier for other developers to work with our code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18ec80306e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>